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

在Swift中测试双引号字符的字符串,swift,string,if-statement,double-quotes,Swift,String,If Statement,Double Quotes,我试图在swift字符串类型中查找双引号字符,代码如下: for char in string { if char == "\"" { debugPrint("I have found a double quote") } } if语句从不捕捉字符串中的双引号 我使用的是Xcode 7.3.1 有什么建议吗?我认为代码甚至不应该编译?(假设string确实是一个字符串。) 试试这个。似乎适合我(相同的Xcode版本): 根据您想做的事情: let str = "

我试图在swift字符串类型中查找双引号字符,代码如下:

for char in string {
    if char == "\"" {
        debugPrint("I have found a double quote")
    }
}
if语句从不捕捉字符串中的双引号

我使用的是Xcode 7.3.1


有什么建议吗?

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

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


根据您想做的事情:

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)

如果我在搜索双引号,则给出的所有示例都将失败。如果我搜索一个“a”,他们都能在字符串中找到它。我想知道我是否在Swift中发现了一个bug?我实际上是在尝试遍历字符串中的字符,以找到以双引号括起来的文本,这样我就可以提取它。如果我在为测试它的工作而设计的单独应用程序中尝试您的示例。嗯!!当我在从文件中读取行之后使用以下代码时,代码将找不到tkns中tk的\“character:init(line:String){super.init()let tkns=line.componentsSeparatedByString(“”)的\“character:init(line:String){print(“我找到了一个引号”)}self.tokens.append(Token(Token:tk))}}有什么想法吗?在for循环中放置一个断点,并通过调试器运行它。我没有足够的数据来知道发生了什么,直到它正确。通过将我正在测试的操作符放入操作符数组中,我解决了操作符问题。疏忽。看起来我唯一遇到麻烦的字符是双引号字符。@doodle我自己测试过这段代码,它对我很有效。如果你分享你正在运行的确切代码,我可以试试。而且,我完全不知道这句话在说什么:“我通过将我正在测试的操作符放在操作符数组中解决了操作符问题。”这是之前的评论。漠视我将发布我正在使用的确切函数代码。我已经能够让它在另一个测试应用程序中工作。正是在这个应用程序中,我从NSTextView中提取了要解析的文本。我还使用Xcode提供的文档模板,所以我也不知道它对读取的文件做了什么。
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)