这个简单的问题使我感到困惑。
外部软件包中的某些函数返回*string
如何在返回的*string
中找到子字符串?
已知的Go函数strings.Index
和Contains
需要string
类型而不是指针。
最佳答案
取消引用指针,因此您获得了string
值。然后,您可以继续进行操作,就好像它不是指针一样。
Spec: Address operators:
对于指针类型为x
的操作数*T
,指针间接指示*x
表示T
指向的x
类型的variable。
例如:
func main() {
p := getPtr()
fmt.Println(strings.Contains(*p, "go"))
fmt.Println(strings.Contains(*p, "yo"))
}
func getPtr() *string {
s := "gopher"
return &s
}
输出(在Go Playground上尝试):
true
false
关于string - 如何在字符串指针中找到子字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60433970/