How to check if two strings have the same words in different order with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "reflect"
    "sort"
    "strings"
)

func haveSameWordsInDifferentOrder(str1, str2 string) bool {
    words1 := strings.Fields(str1)
    words2 := strings.Fields(str2)

    if len(words1) != len(words2) {
        return false
    }

    sort.Strings(words1)
    sort.Strings(words2)

    return reflect.DeepEqual(words1, words2)
}

func main() {
    str1 := "java c# c c++ go";
    str2 := "go c++ java c# c";
    str3 := "go c++ java c# c rust";

    if haveSameWordsInDifferentOrder(str1, str2) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
    
    if haveSameWordsInDifferentOrder(str1, str3) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}



/*
run:

yes
no

*/

 



answered Nov 29, 2024 by avibootz
edited Nov 29, 2024 by avibootz
...