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

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

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, &quot;test&quot;, &quot;test noti&quot;, &quot;result alarm&quot;, &quot;alarm test&quot;)

sentence := &quot;alarm result test&quot;

for i := 0; i &lt; len(words); i++ {
	log.Info(strings.Split(words[i], &quot; &quot;))
}

答案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 (
	&quot;fmt&quot;
	&quot;strings&quot;
)

const s = &quot;alarm result test&quot;

var words = []string{&quot;test&quot;, &quot;test noti&quot;, &quot;result alarm&quot;, &quot;alarm test&quot;}

func main() {
	for _, w := range words {
		var c bool
		for _, substr := range strings.Split(w, &quot; &quot;) {
			c = strings.Contains(s, substr)
			if !c {
				break
			}
		}
		
		fmt.Printf(&quot;%t %s \n&quot;, c, w)
	}
}

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:

确定