golang判断字符是否存在字符串中


本文摘自php中文网,作者尚,侵删。

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

示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package main

import (

"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教程栏目。

以上就是golang判断字符是否存在字符串中的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

go call

分享一个go json 踩坑记录

这家独角兽旅行服务公司,在用 go 进行微服务治理

golang如何复用http.request.body

ketos 笔记 -- 记 go hackathon 2017

golang官方嵌入文件到可执行程序

awesome go!高玩gopher都会参考的go资源集合

go语言proto使用入门

go那些事之helloworld结构

写在 dubbo go 的第五个年头

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...