如何在 Golang 中检查字符串是否包含子字符串?
go programmingserver side programmingprogramming更新于 2025/5/27 12:07:17
我们知道子字符串是字符串中连续的字符序列,为了检查字符串是否包含子字符串,我们有两种选择。
第一种方法是使用内置函数 Contains(),第二种方法是使用自写的逻辑。
strings 包的 Contains() 函数的语法如下所示。
func Contains(s, substr string) bool
在上述语法中,函数 Contains() 中有两个参数。第一个参数是我们试图在其中找到模式的字符串,第二个参数是我们试图找到的模式。
让我们首先考虑第一种方法。
示例 1
考虑下面显示的代码。
package main import ( "fmt" "strings" ) func main() { var name string = "TutorialsPoint" fmt.Println(strings.Contains(name, "Point")) }
输出
如果我们使用命令 go run main.go 运行上述代码,那么我们将在终端中获得以下输出。
true
现在我们已经了解了在上述字符串中查找子字符串的最常用方法,让我们考虑一个工作原理相同但逻辑是自写的代码。
示例 2
考虑下面显示的代码。
package main import ( "fmt" ) func main() { var name string = "TutorialsPoint" var wordToSearch string = "Point" res := checkIfExists(name, wordToSearch) if res { fmt.Println(wordToSearch, "is present inside the string", name) } else { fmt.Println(wordToSearch, "is not present inside the string", name) } } func checkIfExists(name, word string) bool { l := len(name) - len(word) for i := 0; i <= l; i++ { if patternMatch(name, i, word) { return true } } return false } func patternMatch(name string, index int, word string) bool { i := index for j := 0; j < len(word); j++ { if name[i] != word[j] { return false } i++ } return true }
在上面的代码中,函数 checkIfExists() 用于在字符串中查找模式,该函数又调用 patternMatch 函数。
输出
如果我们使用命令 go run main.go 运行上面的代码,那么我们将在终端中获得以下输出。
Point is present inside the string TutorialsPoint