英文:
all words are contained in sentence by golang
问题
如何匹配句子中的所有单词?
单词列表:["test", "test noti", "result alarm", "alarm test"]
句子: "alarm result test"
我期望的结果是这样的:
[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], " "))
}
英文:
How can i match all word in the sentence?
words: ["test", "test noti", "result alarm", "alarm test"]
sentence: "alarm result test"
I expected something like this
[o] test
[x] test noti
[o] result alarm
[o] alarm test
I tried split by words,
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], " "))
}
答案1
得分: 0
请看一下go strings包。它包含了实现你目标所需的必要函数。
以下是一个示例:
package main
import (
"fmt"
"strings"
)
const s = "alarm result test"
var words = []string{"test", "test noti", "result alarm", "alarm test"}
func main() {
for _, w := range words {
var c bool
for _, substr := range strings.Split(w, " ") {
c = strings.Contains(s, substr)
if !c {
break
}
}
fmt.Printf("%t %s \n", c, w)
}
}
https://go.dev/play/p/PhGLePCwhho
英文:
Take a look at go strings package.
It contains necessary functions to achieve your goal.
As an example:
package main
import (
"fmt"
"strings"
)
const s = "alarm result test"
var words = []string{"test", "test noti", "result alarm", "alarm test"}
func main() {
for _, w := range words {
var c bool
for _, substr := range strings.Split(w, " ") {
c = strings.Contains(s, substr)
if !c {
break
}
}
fmt.Printf("%t %s \n", c, w)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论