Go 提供了多种查找字符串的方法: 1. Index 函数查找子字符串的第一个出现位置,如果没有则返回 -1。 2. IndexByte 函数查找单个字符(字节)的第一个出现位置。 3. LastIndex 函数从字符串末尾开始查找子字符串的最后一个出现位置。 4. Contains 函数检查子字符串是否存在,存在返回 true,不存在返回 false。 5. HasPrefix 和 HasSuffix 函数检查字符串是否以子字符串开头或结尾,符合返回 true,否则返回 false。
如何在 Go 中查找字符串
Go 提供了多种方法来查找字符串:
1. 使用 Index
Index 函数返回指定子字符串在字符串中的第一个出现位置,如果没有匹配项,则返回 -1。
立即学习“go语言免费学习笔记(深入)”;
package mainimport ( "fmt" "strings")func main() { str := "Hello, Go!" index := strings.Index(str, "Go") if index == -1 { fmt.Println("Not found") } else { fmt.Println("Found at index:", index) }}
登录后复制
2. 使用 IndexByte
IndexByte 函数类似于 Index,但它适用于单个字符(字节)。
package mainimport ( "fmt" "strings")func main() { str := "Hello, Go!" index := strings.IndexByte(str, 'G') if index == -1 { fmt.Println("Not found") } else { fmt.Println("Found at index:", index) }}
登录后复制
3. 使用 LastIndex
LastIndex 函数与 Index 类似,但它从字符串的末尾开始搜索。
package mainimport ( "fmt" "strings")func main() { str := "Hello, Go Go!" index := strings.LastIndex(str, "Go") if index == -1 { fmt.Println("Not found") } else { fmt.Println("Found at index:", index) }}
登录后复制
4. 使用 Contains
Contains 函数检查字符串中是否包含指定的子字符串,如果包含,则返回 true,否则返回 false。
package mainimport ( "fmt" "strings")func main() { str := "Hello, Go!" contains := strings.Contains(str, "Go") if contains { fmt.Println("Yes, it contains 'Go'") } else { fmt.Println("No, it doesn't contain 'Go'") }}
登录后复制
5. 使用 HasPrefix 和 HasSuffix
HasPrefix 和 HasSuffix 函数检查字符串是否以指定的子字符串开头或结尾,如果符合,则返回 true,否则返回 false。
package mainimport ( "fmt" "strings")func main() { str := "Hello, Go!" hasPrefix := strings.HasPrefix(str, "Hello") hasSuffix := strings.HasSuffix(str, "Go!") if hasPrefix { fmt.Println("Yes, it starts with 'Hello'") } else { fmt.Println("No, it doesn't start with 'Hello'") } if hasSuffix { fmt.Println("Yes, it ends with 'Go!'") } else { fmt.Println("No, it doesn't end with 'Go!'") }}
登录后复制
以上就是golang怎么查找字符串的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2338342.html