您可以使用
strings.Contains()可用于多个子字符串的函数编写自己的实用程序函数。
以下是在完全/部分匹配以及匹配总数的情况下返回布尔值(
true/
false)的示例:
package mainimport ( "fmt" "strings")func checkSubstrings(str string, subs ...string) (bool, int) { matches := 0 isCompleteMatch := true fmt.Printf("String: "%s", Substrings: %sn", 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



