简体   繁体   中英

Swift: How to loop through all characters in a string, and also determine what characters belongs to a specific subset

This Python code loops through all characters in a string and prints out characters that belong to a specific subset.

str = "abcdefg12345"
for ch in str:
    if ch in "ab34":
        print( ch )

How can I translate that code into Swift?

You can create a Set to hold the characters you are searching for, and then use contains to test for inclusion:

let str = "abcdefg12345"
let searchSet = Set("ab34")
for ch in str {
    if searchSet.contains(ch) {
       println(ch)
    }
}

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