我试图使用以下代码在swift String类型中找到双引号字符:
for char in string {
if char == "\"" {
debugPrint("I have found a double quote")
}
}
if语句永远不会捕获字符串中的双引号。
我正在使用Xcode 7.3.1
有任何意见建议吗?
答案 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")
}
}