objective-c - NSScanner 从 NSString 中删除子字符串引用

标签 objective-c cocoa nsstring nsscanner

我有 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/

相关文章:

objective-c - 如何在 objective-c 中使用分数进行计算

cocoa - NSArrayController 和 KVO

objective-c - stringByTrimmingCharactersInSet : is not removing characters in the middle of the string

cocoa - 处理临时字符串的更好方法是什么?

ios - 是否可以更改具有不同类的对象的类类型?

objective-c - 将 UIScrollView 锁定在特定页面上(pagingEnabled)

objective-c - 使用 CoreGraphics 方法发送自动重复键 (Mac OS X Snow Leopard)

objective-c - NSTableView 排序未获得正确的 ID

iphone - 在第二个 View 上更改字符串变量会出错

界面生成器中的 iOS 多行标签