一、字符串包含的定义
字符串包含是指一个字符串是否包含另一个字符串,也就是判断一个字符串是否是另一个字符串的子串。
在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/n/236407.html