所有的单词都包含在由Golang构成的句子中。

huangapple go评论113阅读模式
英文:

all words are contained in sentence by golang

问题

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

单词列表:["test", "test noti", "result alarm", "alarm test"]

句子: "alarm result test"

我期望的结果是这样的:

  1. [o] test
  2. [x] test noti
  3. [o] result alarm
  4. [o] alarm test

我尝试了按单词分割的方法,

  1. var words []string
  2. words = append(words, "test", "test noti", "result alarm", "alarm test")
  3. sentence := "alarm result test"
  4. for i := 0; i < len(words); i++ {
  5. log.Info(strings.Split(words[i], " "))
  6. }
英文:

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

  1. [o] test
  2. [x] test noti
  3. [o] result alarm
  4. [o] alarm test

I tried split by words,

  1. var words []string
  2. words = append(words, &quot;test&quot;, &quot;test noti&quot;, &quot;result alarm&quot;, &quot;alarm test&quot;)
  3. sentence := &quot;alarm result test&quot;
  4. for i := 0; i &lt; len(words); i++ {
  5. log.Info(strings.Split(words[i], &quot; &quot;))
  6. }

答案1

得分: 0

请看一下go strings包。它包含了实现你目标所需的必要函数。

以下是一个示例:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. const s = "alarm result test"
  7. var words = []string{"test", "test noti", "result alarm", "alarm test"}
  8. func main() {
  9. for _, w := range words {
  10. var c bool
  11. for _, substr := range strings.Split(w, " ") {
  12. c = strings.Contains(s, substr)
  13. if !c {
  14. break
  15. }
  16. }
  17. fmt.Printf("%t %s \n", c, w)
  18. }
  19. }

https://go.dev/play/p/PhGLePCwhho

英文:

Take a look at go strings package.
It contains necessary functions to achieve your goal.

As an example:

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;strings&quot;
  5. )
  6. const s = &quot;alarm result test&quot;
  7. var words = []string{&quot;test&quot;, &quot;test noti&quot;, &quot;result alarm&quot;, &quot;alarm test&quot;}
  8. func main() {
  9. for _, w := range words {
  10. var c bool
  11. for _, substr := range strings.Split(w, &quot; &quot;) {
  12. c = strings.Contains(s, substr)
  13. if !c {
  14. break
  15. }
  16. }
  17. fmt.Printf(&quot;%t %s \n&quot;, c, w)
  18. }
  19. }

https://go.dev/play/p/PhGLePCwhho

huangapple
  • 本文由 发表于 2022年1月26日 15:18:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/70859756.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定