Swift:检查字符串是否包含字符?

时间:2015-10-26 13:13:00

标签: string swift character contains

如何检查特定string: String是否包含某个character: Character

2 个答案:

答案 0 :(得分:9)

string.characters.contains(character)

示例:

let string = "Hello, World!"
let character: Character = "e"

if string.characters.contains(character) {
    print("\(string) contains \(character).")
} else {
    print("\(string) doesn't contain \(character).")
}

答案 1 :(得分:0)

let char: Character = "e"

let string: String = "William"

let result = string.rangeOfString("\(char)")

if let result = result {
    //The string contains the character
    print("It contains")
}else{
    //The string doesn't contain the character
    print("It doesn't contain")
}