golang判断字符是否存在字符串中的方法:

判断子字符串或字符在父字符串中出现的位置(索引)

Index 返回字符串 str 在字符串 s 中的索引( str 的第一个字符的索引),-1 表示字符串 s 不包含字符串 str :

strings.Index(s, str string) int

LastIndex 返回字符串 str 在字符串 s 中最后出现位置的索引( str 的第一个字符的索引),-1 表示字符串 s 不包含字符串 str :

strings.LastIndex(s, str string) int

如果 ch 是非 ASCII 编码的字符,建议使用以下函数来对字符进行定位:

strings.IndexRune(s string, ch int) int

示例:

package mainimport ("fmt""strings")func main() {var str string = "Hi, I'm Marc, Hi."fmt.Printf("The position of \"Marc\" is: ")fmt.Printf("%d\n", strings.Index(str, "Marc"))fmt.Printf("The position of the first instance of \"Hi\" is: ")fmt.Printf("%d\n", strings.Index(str, "Hi"))fmt.Printf("The position of the last instance of \"Hi\" is: ")fmt.Printf("%d\n", strings.LastIndex(str, "Hi"))fmt.Printf("The position of \"Burger\" is: ")fmt.Printf("%d\n", strings.Index(str, "Burger"))}

更多golang知识请关注PHP中文网golang教程栏目。

更多相关文章

  1. golang怎么把字符串转成Int类型
  2. golang怎么拼接字符串数组
  3. golang如何判断字符串是否为空
  4. 常见的 Go 处理字符串的技巧
  5. go语言中一些字符串操作介绍
  6. 用Go实现字符串的逆序
  7. 关于 Golang 字符串 格式化
  8. go语言如何实现字符串转数组
  9. go语言中数字如何转字符串

随机推荐

  1. Android AudioRecord介绍与Android 6.0后
  2. Android(安卓)实时视频采集
  3. android之Uri的使用简介\Uri与path相互
  4. android异步更新UI
  5. Android——消息机制
  6. 基于rtmp协议流媒体开发值得参考文章
  7. 【Android】Android SDK下载和更新失败的
  8. Android如何发邮件?
  9. 基于Android Volley的网络请求工具
  10. 关于android WebViewClient和WebChromeCl