Go 標(biāo)準(zhǔn)包 strings 學(xué)習(xí)(5) HasPrefix,HasSuffix,Index,IndexAny,IndexRun
https://pkg.go.dev/strings@go1.20.4#HasPrefix
func?HasPrefix
HasPrefix tests whether the string s begins with prefix.
翻譯
HasPrefix測(cè)試字符串s是否以prefix開(kāi)頭。
例子
輸出
true false true
理解:
簡(jiǎn)單,夏一鴿

func?HasSuffix
HasSuffix tests whether the string s ends with suffix.
HasSuffix測(cè)試字符串s是否以suffix結(jié)尾。
例子
輸出?true false false true
理解:
簡(jiǎn)單,下一個(gè)

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的第一個(gè)實(shí)例的索引,如果s中不存在substr則返回-1。
舉例
輸出
4 -1
理解:
返回第二個(gè)字符串在第一個(gè)字符串中第一次出現(xiàn)的位置,沒(méi)有就返回-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中任何來(lái)自char的Unicode碼點(diǎn)的第一個(gè)實(shí)例的索引,如果s中沒(méi)有來(lái)自char的Unicode碼點(diǎn),則返回-1。
舉例
輸出
2 -1
理解:
返回第二個(gè)字符串中任意字符在第一個(gè)字符串中,出現(xiàn)的位置,沒(méi)有就返回-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)的第一個(gè)Unicode碼點(diǎn)的索引s,如果不滿足則返回-1。
例子
輸出
7 -1
理解
先定義一個(gè)func,func可以判斷是否是漢字,如果是漢字就返回true,不是就返回false
調(diào)用strings.IndexFunc()方法,第一個(gè)參數(shù)傳一個(gè)字符串
將func當(dāng)作參數(shù)傳入strings.IndexFunc的第二個(gè)參數(shù)位置,相當(dāng)于自定義規(guī)則
方法會(huì)返回根據(jù)規(guī)則判斷成功的字符的下標(biāo),如果沒(méi)有就返回-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碼點(diǎn)r的第一個(gè)實(shí)例的索引,如果rune不在s中,則返回-1。如果r為utf8.RuneError,它返回任何無(wú)效UTF-8字節(jié)序列的第一個(gè)實(shí)例。
例子
輸出
4 -1
理解
簡(jiǎn)單可以理解為第二個(gè)字符參數(shù)在第一個(gè)字符串中的下標(biāo)位置,沒(méi)有返回-1