且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

前往:如何检查一个字符串是否包含多个子字符串?

更新时间:2022-11-17 10:56:10

您可以使用 strings.Contains()编写自己的实用程序函数,该函数可用于多个子字符串.

You can write your own utility function using strings.Contains() that can work for multiple sub-strings.

以下是在完全/部分匹配以及匹配总数的情况下返回布尔值( true / false )的示例:

Here's an example that returns Boolean (true/false) in case of complete / partial match and the total number of matches:

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