简体   繁体   中英

Swift string compare characters

I am looking to compare a string that the user enters to 3 other strings. If the user entered string has any of the characters that the other strings contain I want to do one thing and if not something else

case 1: string1 = abc string2 = abc string3 = abc

userEnter = fgh

> since none of the letters match do one thing

case 2: string1 = abc string2 = fbc string3 = abc

userEnter = fgh

> one letter from userEnter is found in the other 3 strings do another thing...

Not sure how to compare strings in swift at all or how to access individual characters. I am used to C where everything is a char array..

Strings in Swift are a different different kid of beast compared to C and are not just arrays of characters (there is a nice article at the Swift blog which I would suggest you to read, BTW). In your case you can use characters property of the String type, which is basically a view that gives you access to individual characters in the string.

For example, you could do:

let strings = ["abc", "abc", "abc"]

let chars = strings.reduce(Set<Character>()) { 
    (var output: Set<Character>, string: String) -> Set<Character> in

    string.characters.forEach() {
        output.insert($0)
    }

    return output
}

let test = "fgh"

if test.characters.contains({ chars.contains($0) }) {
    print("Do one thing")
} else {
    print("Do another thing")
}

In the above code strings array contains all your 3 compare-to strings. Then there is a set chars created out of them that contains all the individual characters from all of the strings. And finally there is a test which contains user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM