strings.Contains(str_to_check, substr)
只接受一个子字符串作为检查对象,如果不想重复使用strings.Contains()
,如何检查多个子字符串?
例如:strings.Contains(str_to_check, substr1, substr2)
您可以使用 strings.Contains()
编写自己的实用函数,以便适用于多个子字符串。
以下是一个示例,它返回布尔值(true
/false
),以表明是否完全/部分匹配,以及匹配的总数:
package main
import (
"fmt"
"strings"
)
func checkSubstrings(str string, subs ...string) (bool, int) {
matches := 0
isCompleteMatch := true
fmt.Printf("String: \"%s\", Substrings: %s\n", str, subs)
for _, sub := range subs {
if strings.Contains(str, sub) {
matches += 1
} else {
isCompleteMatch = false
}
}
return isCompleteMatch, matches
}
func main() {
isCompleteMatch1, matches1 := checkSubstrings("Hello abc, xyz, abc", "abc", "xyz")
fmt.Printf("Test 1: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch1, matches1)
fmt.Println()
isCompleteMatch2, matches2 := checkSubstrings("Hello abc, abc", "abc", "xyz")
fmt.Printf("Test 2: { isCompleteMatch: %t, Matches: %d }\n", isCompleteMatch2, matches2)
}
输出:
String: "Hello abc, xyz, abc", Substrings: [abc xyz]
Test 1: { isCompleteMatch: true, Matches: 2 }
String: "Hello abc, abc", Substrings: [abc xyz]
Test 2: { isCompleteMatch: false, Matches: 1 }
是的,您可以在不多次调用strings.Contains()
的情况下完成此操作。
如果您事先知道子字符串,则使用正则表达式检查最简单。如果要检查的字符串很长,并且有相当多的子字符串,则比多次调用strings.Contains
更快。
示例https://play.golang.org/p/7PokxbOOo7:
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile(`first|second|third`)
func main() {
fmt.Println(re.MatchString("This is the first example"))
fmt.Println(re.MatchString("This is the second example after first"))
fmt.Println(re.MatchString("This is the third example"))
fmt.Println(re.MatchString("This is the forth example"))
}
输出:
true
true
true
false
strings.Contains()
可能更好,虽然最好测试一下你的代码是否对性能至关重要。regexp
和suffixarray
的组合。来自文档的说明如下:
包suffixarray使用内存后缀数组以对数时间实现子字符串搜索。
package main
import (
"fmt"
"index/suffixarray"
"regexp"
"strings"
)
func main() {
fmt.Println(contains("first secondthird", "first", "second", "third"))
fmt.Println(contains("first secondthird", "first", "10th"))
}
func contains(str string, subStrs ...string) bool {
if len(subStrs) == 0 {
return true
}
r := regexp.MustCompile(strings.Join(subStrs, "|"))
index := suffixarray.New([]byte(str))
res := index.FindAllIndex(r, -1)
exists := make(map[string]int)
for _, v := range subStrs {
exists[v] = 1
}
for _, pair := range res {
s := str[pair[0]:pair[1]]
exists[s] = exists[s] + 1
}
for _, v := range exists {
if v == 1 {
return false
}
}
return true
}
(在Go Playground中)
package main
import (
"fmt"
"strings"
)
func main() {
listStrings := []string{"d", "x"}
for _,value:= range listStrings {
if strings.Contains("mystring", value) {
fmt.Println("Contains")
break
}
}
}