NSString stringByReplacingOccurrencesOfString无法正确使用转义字符

时间:2013-08-14 15:20:37

标签: objective-c nsstring

我想从"移除NSString,但它无法解决问题。

该字符串来自XMLParser:

- (void)parser:(NSXMLParser *)parser
 didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI
 qualifiedName:(NSString *)qName
{
  if([elementName isEqualToString:@"li"]){
      _isAnswer = NO;
  }else if([elementName isEqualToString:@"span"]){
     NSString *immutableString = [NSString stringWithString:currentElementValue];//currentElementValue is myMutableString
     NSString* myString = [immutableString stringByReplacingOccurrencesOfString:@"\"" withString:@"00000"];
     myString = [myString stringByReplacingOccurrencesOfString:@"״" withString:@"00000"];
     myString = [myString stringByReplacingOccurrencesOfString:@"“" withString:@"00000"];
     myString = [myString stringByReplacingOccurrencesOfString:@"”" withString:@"00000"];          

NSLog(@“myString - ”,myString);       }     }

  • xml中的字符串包含"

  • 日志:

    myString - this is the " string
    

    而不是:

    myString - this is the 00000 string
    

1 个答案:

答案 0 :(得分:0)

我已经测试了您的代码,这里的一切正常。代码中的某个地方存在问题,您没有共享...

    NSString *str = @"LOL \"... ";

    NSLog(@"%@",str);
    str = [str stringByReplacingOccurrencesOfString:@"\"" withString:@"00000"];
    NSLog(@"%@",str);

这是输出:

>>  LOL "... 
>>  LOL 00000... 

告诉我们您的字符串是如何初始化的


编辑:

1)首先确保它是"字符,而不是“,”或“

2)尝试这样的事情,它与我的第一个答案结果相同。

    NSString *str = @"LOL \"... ";

    unichar const maskChar = 0x0022; // Code of " char
    NSString *mask = [[NSString alloc] initWithCharacters:&maskChar length:1];

    NSLog(@"%@",str);
    str = [str stringByReplacingOccurrencesOfString:mask withString:@"00000"];
    NSLog(@"%@",str);

如果第二个解决方案不起作用,则不是"字符