所有单词都包含在 golang 的句子中

我如何匹配句子中的所有单词?


词:[“测试”,“测试通知”,“结果警报”,“警报测试”]


句子:“报警结果测试”


我期待这样的事情


[o] test

[x] test noti

[o] result alarm

[o] alarm test

我试着用文字分开,


var words []string

words = append(words, "test", "test noti", "result alarm", "alarm test")


sentence := "alarm result test"


for i := 0; i < len(words); i++ {

    log.Info(strings.Split(words[i], " "))

}


慕的地6264312
浏览 121回答 1
1回答

茅侃侃

看看go strings包。它包含实现目标所需的功能。举个例子:package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "strings")const s = "alarm result test"var words = []string{"test", "test noti", "result alarm", "alarm test"}func main() {&nbsp; &nbsp; for _, w := range words {&nbsp; &nbsp; &nbsp; &nbsp; var c bool&nbsp; &nbsp; &nbsp; &nbsp; for _, substr := range strings.Split(w, " ") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c = strings.Contains(s, substr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if !c {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%t %s \n", c, w)&nbsp; &nbsp; }}https://go.dev/play/p/PhGLePCwhho
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go