在Go语言中没有startswith和endswith函数吗?

huangapple go评论88阅读模式
英文:

No startswith,endswith functions in Go?

问题

只是好奇想知道:为什么Go编程语言的标准库中没有像startswith、endswith等标准函数?

英文:

Just curious to findout: why aren't there standard functions like startswith, endswith, etc as part of the standard libraries in the Go programming language?

答案1

得分: 318

strings 包含 HasPrefixHasSuffix

import "strings"

startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true

play.golang.org

英文:

The strings package contains HasPrefix and HasSuffix.

import "strings"

startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true

play.golang.org

答案2

得分: 4

如果您正在使用字节,可以使用字节包中的这些函数:

package main

import (
   "bytes"
   "fmt"
)

func main() {
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}

与先转换为字符串相比,这样做的成本较低。如果您从HTTP请求中读取数据或从本地文件中读取数据,这将非常有用。

英文:

If you are working with bytes, you can use these functions from the bytes
package:

package main

import (
   "bytes"
   "fmt"
)

func main() {
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("Go")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("C")))
   fmt.Println(bytes.HasPrefix([]byte("Gopher"), []byte("")))
}

It will be less costly than converting to string first. Useful if you are reading
in from an HTTP request, or reading from a local file.

  • <https://golang.org/pkg/bytes#HasPrefix>
  • <https://golang.org/pkg/bytes#HasSuffix>

huangapple
  • 本文由 发表于 2012年11月6日 11:45:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/13244048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定