我有 NSString's
,形式为 Johnny 喜欢“吃”苹果
。我想从字符串中删除引号,以便。
Johnny likes "eating" apples
变成了
John likes 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;
}
最佳答案
这段代码很hacky,但似乎产生了你想要的输出。
它没有使用意外的输入进行测试(字符串不是所描述的形式,零字符串...),但应该可以帮助您开始。
- (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 类的文档以找出我缺少的内容,并且必须注意手动字符串修剪。
关于objective-c - NSScanner 从 NSString 中删除子字符串引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135756/