栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您可以使用

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/436317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号