英文:
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 包含 HasPrefix 和 HasSuffix。
import "strings"
startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true
英文:
The strings package contains HasPrefix and HasSuffix.
import "strings"
startsWith := strings.HasPrefix("prefix", "pre") // true
endsWith := strings.HasSuffix("suffix", "fix") // true
答案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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论