【问题标题】:Testing string for double quote characters in Swift在 Swift 中测试双引号字符的字符串
【发布时间】:2016-07-15 11:17:07
【问题描述】:

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

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

if 语句从不捕获字符串中的双引号。

我正在使用 Xcode 7.3.1

对cmets有什么建议吗?

【问题讨论】:

    标签: swift string if-statement double-quotes


    【解决方案1】:

    取决于你想做什么:

    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 中发现了一个错误?
    • 我实际上是在尝试遍历字符串中的字符以查找用双引号括起来的文本,以便提取它。
    • 如果我在为测试而设计的单独应用程序中尝试您的示例,它可以工作。嗯嗯!
    • 当我从文件中读取该行后使用以下代码时,该代码将找不到 \" 字符: init(line: String) { super.init() let tkns = line.componentsSeparatedByString (" ") for tk in tkns { if tk.containsString("\"") { print("I found a quote") } self.tokens.append(Token(token: tk)) } } 有什么想法吗?跨度>
    • 在 for 循环中放置一个断点并通过调试器运行它。我没有足够的数据来了解发生了什么
    【解决方案2】:

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

    试试这个。似乎对我有用(相同的 Xcode 版本):

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

    【讨论】:

    • 仍然顺其自然。我通过将我正在测试的运算符放在运算符数组中来解决运算符问题。一个疏忽。看来我唯一遇到问题的字符是双引号字符。
    • @doodle 我自己测试过这段代码,它对我有用。如果你分享你正在运行的确切代码,我可以试试。
    • 另外,我完全不知道这句话在说什么:“我通过将我正在测试的运算符放在运算符数组中来解决运算符问题。”
    • 这是较早的评论。漠视。我将发布我正在使用的确切功能代码。
    • 我已经能够让它在另一个测试应用程序中工作。正是在这个应用程序中,我一直在从 NSTextView 中解析出文本。另外我正在使用 Xcode 提供的文档模板,所以我也不知道它对读取的文件做了什么。
    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 2014-09-26
    • 2014-11-27
    • 2011-04-12
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多