strings.Contains(str_to_check, substr)仅使用一个参数作为要检查的子字符串,如何检查多个子字符串而不strings.Contains()重复使用?
strings.Contains(str_to_check, substr)
strings.Contains()
例如。 strings.Contains(str_to_check, substr1, substr2)
strings.Contains(str_to_check, substr1, substr2)
您可以使用strings.Contains()可用于多个子字符串的函数编写自己的实用程序函数。
以下是在完全/部分匹配以及匹配总数的情况下返回布尔值(true/ false)的示例:
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 }
这是实时示例:https : //play.golang.org/p/Xka0KfBrRD