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

1 Answer

0 votes
import Foundation

func haveSameWordsinDifferentOrder(_ str1: String, _ str2: String) -> Bool {
    let words1 = str1.split(separator: " ").map { String($0) }.sorted()
    let words2 = str2.split(separator: " ").map { String($0) }.sorted()
    
    return words1 == words2
}

let string1 = "java c# c c++ swift";
let string2 = "swift c++ java c# c";
let string3 = "swift c++ java c# c python";

if haveSameWordsinDifferentOrder(string1, string2) {
    print("yes")
} else {
    print("no")
}

if haveSameWordsinDifferentOrder(string1, string3) {
    print("yes")
} else {
    print("no")
}



/*
run:

yes
no

*/

 



answered Nov 29, 2024 by avibootz
...