Golang 用于检查字符串是否包含子字符串
子字符串是字符串中的一小部分,而Golang中的字符串是字符的集合。由于Go中的字符串是不可变的,在生成后无法修改。但是,通过将字符串连接或添加到现有字符串中,可以创建新的字符串。作为Go中的内置类型,字符串类型可以像任何其他数据类型一样以多种方式使用。
语法
strings.Contains(str,substring string)
要确定一个字符串是否包含特定的子字符串, 使用 Contains(s, substr string) bool 函数。 如果在提供的字符串中找到子字符串,将返回一个指示其存在的布尔值。
strings.Index(str, substring string)
The int函数index(s, str string) 用于确定给定字符串中指定子字符串的第一个实例的索引。如果子字符串缺失,它会返回-1,否则返回子字符串在字符串中的索引。
strings.Index(str, substring string)
函数index(s, str string)用于确定给定字符串中指定子字符串的第一个实例的索引。如果子字符串缺失,它将返回-1,否则返回子字符串在字符串中的索引。
步骤
- 步骤1 - 创建一个main包,并声明fmt(格式包)和strings包
-
步骤2 - 创建一个main函数,在该函数中创建一个字符串mystr
-
步骤3 - 使用字符串函数检查字符串是否包含子字符串
-
步骤4 - 打印输出
示例1
在这个示例中,我们将看到如何使用内置函数strings.Contains()检查字符串是否包含子字符串。输出将是一个布尔值打印到控制台上。让我们通过代码和算法来轻松理解概念。
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "Hello,alexa!" //create string
fmt.Println("The string created here is:", mystr)
substring := "alexa" //hold substring
fmt.Println("The substring from the string is:", substring)
fmt.Println("Whether the substring is present in string or not?")
fmt.Println(strings.Contains(mystr, substring)) //use built-in function to check if substring is present in string
}
输出
The string created here is: Hello,alexa!
The substring from the string is: alexa
Whether the substring is present in string or not?
true
示例2
在这个示例中,我们将看到如何使用strings.Index()函数来检查一个字符串是否包含子串。
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "Hello, alexa!" //create string
fmt.Println("The string created here is:", mystr)
substring := "alexa" //substring
fmt.Println("The substring from the string is:", substring)
fmt.Println("Whether the string contains the substring or not?")
if strings.Index(mystr, substring) >= 0 { //check if condition is true print the statement
fmt.Println("The string contains the substring.")
} else {
fmt.Println("The string does not contain the substring.")
}
}
输出
The string created here is: Hello, alexa!
The substring from the string is: alexa
Whether the string contains the substring or not?
The string contains the substring.
示例3
在此示例中,我们将看到如何使用for循环和strings.Index()函数来查找一个字符串中是否包含子字符串。
package main
import (
"fmt"
"strings"
)
func main() {
mystr := "Hello, alexa!" //create string
fmt.Println("The string created here is:", mystr)
substring := "alexa" //hold substring
fmt.Println("The substring present here is:", substring)
fmt.Println("Whether the substring is present in string or not?")
found := false
for i := 0; i < len(mystr); i++ {
if strings.Index(mystr[i:], substring) == 0 { //check if substring is present in string or not
found = true
break
}
}
if found {
fmt.Println("The string has substring in it.")
} else {
fmt.Println("The string does not have substring in it.")
}
}
输出
The string created here is: Hello, alexa!
The substring present here is: alexa
Whether the substring is present in string or not?
The string has substring in it.
结论
我们执行了三个示例,检查一个字符串是否包含子字符串的程序。在第一个示例中,我们使用了strings.Contains()函数,在第二个示例中,我们使用了strings.Index()函数,在第三个示例中,我们使用了for循环和前面的内置函数。