Home > database >  Golang Compare Two Strings contains same words
Golang Compare Two Strings contains same words

Time:05-18

I am trying check if an array contains a particular word with another array like so:

  • Example: "3 of hearts" and "5 of hearts" match because they are both hearts and should return true.

  • Example: "7 of hearts" and "7 of clubs" match because they both have the value 7 and should return true.

  • Example: "Jack of spades" only matches another "Jack of spades" and should return true.

How would I go about doing this in golang. I tried a bunch of steps and I'm back in square one what I have so far is this:

func compare(firstString, secondString string) bool {
    return false
}

compare("3 of hearts", "5 of hearts")
## This should return true

CodePudding user response:

I'm fairly new to golang but the best way to get this without needing to loop twice would be:

func compare(firstString, secondString string) bool {
    f, s := strings.Split(f, " "), strings.Split(secondString, " ")
    if f[0] == s[0] || f[2] == f[2] {
        return true
    }
    return false
}

compare("3 of hearts", "5 of hearts")
## This should return true

compare("7 of hearts", "7 of clubs")
## This should return true

compare("Jack of spades", "Jack of spades")
## This should return true

compare("5 of hearts", "7 of clubs")
## This should return false

CodePudding user response:

func compare(f, s string) bool {
    arr1, arr2 := strings.Split(f, " "), strings.Split(s, " ")
    for _, v1 := range arr1 {
        for _, v2 := range arr2 {
            if v1 == v2 {
                return true
            }
        }
    }
    return false
}

go playground

  • Related