NSScanner从NSString中删除子串引号

时间:2011-02-27 20:33:57

标签: objective-c cocoa nsstring nsscanner

我以NSString's的形式Johnny 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;
}

1 个答案:

答案 0 :(得分:2)

这段代码很简陋,但似乎产生了你想要的输出 它没有使用意外输入进行测试(字符串不是所描述的形式,nil string ...),但应该让你开始。

- (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类的文档,以找出我所缺少的内容,并且必须注意手动修剪字符串。