Home > Back-end >  all words are contained in sentence by golang
all words are contained in sentence by golang

Time:01-26

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], " "))
}

CodePudding user response:

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)
    }
}

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

  •  Tags:  
  • Related