2011-02-27 64 views
1

我有NSString's的形式Johnny likes "eating" apples。我想从我的字符串中删除引号以便。NSScanner从NSString中删除子串报价

约翰尼喜欢 “吃” 苹果

成为

约翰喜欢苹果

我一直在玩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; 
} 
+0

请发布您的错误/崩溃日志。 – Dominic 2011-02-27 20:50:46

回答

2

此代码是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的资料推测,我错过了什么,而不得不照顾有手动微调的字符串。

+0

这似乎工作得很好。添加了一个检查,以确保参数不是在路上,我认为这很好。谢谢! – Ternary 2011-02-28 01:06:13