欢迎光临散文网 会员登陆 & 注册

Go 标准包 strings 学习(5) HasPrefix,HasSuffix,Index,IndexAny,IndexRun

2023-05-05 13:23 作者:取悦疾风  | 我要投稿

https://pkg.go.dev/strings@go1.20.4#HasPrefix

func HasPrefix

HasPrefix tests whether the string s begins with prefix.

翻译

HasPrefix测试字符串s是否以prefix开头。

例子

输出

true false true

理解:

简单,夏一鸽

func HasSuffix

HasSuffix tests whether the string s ends with suffix.

HasSuffix测试字符串s是否以suffix结尾。

例子

输出 true false false true

理解:

简单,下一个

func Index

Index returns the index of the first instance of substr in s, or -1 if substr is not present in s.

Index返回s中substr的第一个实例的索引,如果s中不存在substr则返回-1。

举例

输出

4 -1

理解:

返回第二个字符串在第一个字符串中第一次出现的位置,没有就返回-1

func IndexAny

IndexAny returns the index of the first instance of any Unicode code point from chars in s, or -1 if no Unicode code point from chars is present in s.

IndexAny返回s中任何来自char的Unicode码点的第一个实例的索引,如果s中没有来自char的Unicode码点,则返回-1。

举例

输出

2 -1

理解:

返回第二个字符串中任意字符在第一个字符串中,出现的位置,没有就返回-1

func IndexByte

IndexFunc returns the index into s of the first Unicode code point satisfying f(c), or -1 if none do.

IndexFunc返回满足f(c)的第一个Unicode码点的索引s,如果不满足则返回-1。

例子

输出

7 -1

理解

先定义一个func,func可以判断是否是汉字,如果是汉字就返回true,不是就返回false

调用strings.IndexFunc()方法,第一个参数传一个字符串

将func当作参数传入strings.IndexFunc的第二个参数位置,相当于自定义规则

方法会返回根据规则判断成功的字符的下标,如果没有就返回-1

func IndexRune

IndexRune returns the index of the first instance of the Unicode code point r, or -1 if rune is not present in s. If r is utf8.RuneError, it returns the first instance of any invalid UTF-8 byte sequence.

IndexRune返回Unicode码点r的第一个实例的索引,如果rune不在s中,则返回-1。如果r为utf8.RuneError,它返回任何无效UTF-8字节序列的第一个实例。

例子

输出

4 -1

理解

简单可以理解为第二个字符参数在第一个字符串中的下标位置,没有返回-1

Go 标准包 strings 学习(5) HasPrefix,HasSuffix,Index,IndexAny,IndexRun的评论 (共 条)

分享到微博请遵守国家法律