Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

all words are contained in sentence by golang

How can i match all word in the sentence?

words: ["test", "test noti", "result alarm", "alarm test"]

sentence: "alarm result test"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading