【问题标题】:Remove double quotes from NSString从 NSString 中删除双引号
【发布时间】:2011-01-08 15:39:54
【问题描述】:

如何从 NSString 中删除双引号。示例:

//theMutableString: "Hello World"

[theMutableString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:(NSRange){0,[theMutableString length]}]

它似乎不起作用,也许是因为我不得不转义 replaceOccurrencesOfString 中的 "?

【问题讨论】:

  • 我认为您使用 [mString length] 来获取 theMutableString 的长度是一个错字?
  • 是的,谢谢你接听。

标签: objective-c nsstring


【解决方案1】:

如果您使用 NSMakeRange(0, [theMutableString length]) 而不是尝试强制转换内联结构会发生什么?

【讨论】:

    【解决方案2】:

    使用NSMakeRange 函数代替您的演员表。这会起作用的:

    [mString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mString length])];
    

    【讨论】:

    • 是的,我可以确认。它可以在没有 NSMakeRange 的情况下工作(尽管我鼓励使用 NSMakeRange)。
    • 是的,我认为这不是问题的根源,因为它对我也适用(尽管使用NSMakeRange 可能更好)。
    【解决方案3】:

    假设 mString 位是错字。我跑了这段代码,结果如预期的那样

    NSMutableString * theMutableString = [[NSMutableString alloc] initWithString:@"\"Hello World!\""];
    NSLog(@"%@",theMutableString);
    
    [theMutableString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:(NSRange){0,[theMutableString length]}];
    
    NSLog(@"%@",theMutableString);
    
    [theMutableString release];
    

    输出

    2010-01-23 15:49:42.880 Stringtest[2039:a0f] "Hello World!"
    2010-01-23 15:49:42.883 Stringtest[2039:a0f] Hello World!
    

    所以 mString 是您的问题中的拼写错误,那么您的代码是正确的,而问题出在其他地方。如果 mString 是您代码中的拼写错误,那就是问题所在。

    【讨论】:

      【解决方案4】:

      我的工作完美(我复制粘贴了你的替换行),NSMakeRange 和内联结构转换。你确定你的 NSString 中的引号真的是 ASCII 字符 0x22 吗?

      【讨论】:

        【解决方案5】:

        你可以使用

        string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];
        

        【讨论】:

          【解决方案6】:

          这个怎么样?

          NSCharacterSet *quoteCharset = [NSCharacterSet characterSetWithCharactersInString:@"\""];
          NSString *trimmedString = [toBeTrimmedString stringByTrimmingCharactersInSet:quoteCharset];
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-02-18
            • 2017-02-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-15
            • 2016-02-15
            相关资源
            最近更新 更多