一、字元串包含的定義
字元串包含是指一個字元串是否包含另一個字元串,也就是判斷一個字元串是否是另一個字元串的子串。
在Go語言中,strings包中提供了若干個函數來判斷一個字元串是否包含另一個字元串,分別是Contains、ContainsAny、ContainsRune和Index、IndexAny、IndexByte、IndexRune等函數。
二、Contains函數
Contains函數用於判斷一個字元串是否包含另一個字元串,返回值為布爾型。
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "hello world"
str2 := "world"
// 判斷str1是否包含str2
if strings.Contains(str1, str2) {
fmt.Printf("%s contains %s\n", str1, str2)
} else {
fmt.Printf("%s does not contain %s\n", str1, str2)
}
}
運行以上代碼,輸出結果為:
hello world contains world
三、Index函數
Index函數用於返回子串在父串中第一次出現的位置,如果沒有找到則返回-1。
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "hello world"
str2 := "world"
// 獲取str2在str1中第一次出現的位置
index := strings.Index(str1, str2)
if index != -1 {
fmt.Printf("%s first appears in %s at position %d\n", str2, str1, index)
} else {
fmt.Printf("%s does not appear in %s\n", str2, str1)
}
}
運行以上代碼,輸出結果為:
world first appears in hello world at position 6
四、ContainsAny函數
ContainsAny函數用於判斷一個字元串是否包含任意一個Unicode代碼點集合中的字元,返回值為布爾型。
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "hello 世界"
str2 := "世"
// 判斷str1是否包含任何一個str2中的字元
if strings.ContainsAny(str1, str2) {
fmt.Printf("%s contains %s\n", str1, str2)
} else {
fmt.Printf("%s does not contain %s\n", str1, str2)
}
}
運行以上代碼,輸出結果為:
hello 世界 contains 世
五、IndexRune函數
IndexRune函數用於返回某個Unicode代碼點在父串中第一次出現的位置,如果沒有找到則返回-1。
package main
import (
"fmt"
"strings"
)
func main() {
str := "hello 世界"
// 獲取世在str中第一次出現的位置
index := strings.IndexRune(str, '世')
if index != -1 {
fmt.Printf("%s first appears in %s at position %d\n", "世", str, index)
} else {
fmt.Printf("%s does not appear in %s\n", "世", str)
}
}
運行以上代碼,輸出結果為:
世 first appears in hello 世界 at position 6
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/236407.html