在Swift中测试双引号字符的字符串

时间:2016-07-15 01:25:20

标签: swift string if-statement double-quotes

我试图使用以下代码在swift String类型中找到双引号字符:

for char in string {
    if char == "\"" {
        debugPrint("I have found a double quote")
    }
}

if语句永远不会捕获字符串中的双引号。

我正在使用Xcode 7.3.1

有任何意见建议吗?

2 个答案:

答案 0 :(得分:3)

取决于您想要做什么:

let str = "Hello \"World\""

// If you simply want to know if the string has a double quote
if str.containsString("\"") {
    print("String contains a double quote")
}

// If you want to know index of the first double quote
if let range = str.rangeOfString("\"") {
    print("Found double quote at", range.startIndex)
}

// If you want to know the indexes of all double quotes
let indexes = str.characters.enumerate()
                .filter { $1 == "\"" }
                .map { $0.0 }
print(indexes)

答案 1 :(得分:1)

我认为代码甚至不应该编译? (假设string确实是一个字符串。)

试试这个。似乎适合我(相同的Xcode版本):

for char in string.characters {
    if char == "\"" {
        print("I have found a double quote")
    }
}