1

NSString'sJohnny likes "eating" apples. 我想从我的字符串中删除引号。

强尼喜欢“吃”苹果

变成

约翰喜欢苹果

我一直在使用 NSScanner 来解决这个问题,但我遇到了一些崩溃。

- (NSString*)clean:(NSString*) _string
{   
   NSString *string = nil;
   NSScanner *scanner = [NSScanner scannerWithString:_string];
   while ([scanner isAtEnd] == NO)  
   {
      [scanner scanUpToString:@"\"" intoString:&string];
      [scanner scanUpToString:@"\"" intoString:nil];
      [scanner scanUpToString:@"." intoString:&string]; // picked . becuase it's not in the string, really just want rest of string scanned
   }
   return string;
}
4

1 回答 1

2

这段代码很hacky,但似乎产生了你想要的输出。
它没有使用意外输入进行测试(字符串不是所描述的形式,nil 字符串...),但应该可以帮助您入门。

- (NSString *)stringByStrippingQuottedSubstring:(NSString *) stringToClean
{   
    NSString *strippedString,
             *strippedString2;

    NSScanner *scanner = [NSScanner scannerWithString:stringToClean];

    [scanner scanUpToString:@"\"" intoString:&strippedString];                          // Getting first part of the string, up to the first quote
    [scanner scanUpToString:@"\" " intoString:NULL];                                    // Scanning without caring about the quoted part of the string, up to the second quote

    strippedString2 = [[scanner string] substringFromIndex:[scanner scanLocation]];     // Getting remainder of the string

    // Having to trim the second part of the string
    // (Cf. doc: "If stopString is present in the receiver, then on return the scan location is set to the beginning of that string.")
    strippedString2 = [strippedString2 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\" "]];

    return [strippedString stringByAppendingString:strippedString2];
}

我稍后会回来(很多)清理它,并深入研究 NSScanner 类的文档以找出我缺少的内容,并且必须注意手动修剪字符串。

于 2011-02-27T21:22:11.747 回答