0

我们想用特定字符分割字符串而不删除字符。例如,如果输入是:if (x>4) then {x = 1} 输出需要是:if, (, x, >, 4, ), then, {, x, =, 1, }

  • 我们尝试使用characterSetWithCharactersInString,但它从字符串中删除了字符..

谢谢 !

4

2 回答 2

0

看看NSScanner

然后做类似的事情

 NSScanner *scanner = [NSScanner scannerWithString:myString];
 BOOL foundIf = [scanner scanString:@"if" intoString:nil];
 // etc...
于 2012-06-03T13:23:08.430 回答
0

如果您还没有弄清楚,以下将起作用:

NSString *input = @"if (x>4) then {x = 1}";
NSMutableArray *splitArray = [NSMutableArray array];    
NSCharacterSet *specialChars = [NSCharacterSet characterSetWithCharactersInString:@"(){}[]<>{}="];    
NSScanner *scanner = [NSScanner scannerWithString:input];    
while (![scanner isAtEnd])
{
    NSString *buffer;
    if ([scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:&buffer])
    {
        [splitArray addObject:buffer];            
    }
    else if ([scanner scanCharactersFromSet:specialChars intoString:&buffer])
    {
        [splitArray addObject:buffer];            
    }
    else 
    {
        [scanner setScanLocation:[scanner scanLocation] + 1];
    }
}    
NSLog(@"%@", splitArray);

您可以将任何您想要的字符添加到 specialChars。

PS:我今天第一次读到 NSScanner,这是一个很好的练习,可以真正使用它!我建议你通过这个https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/Scanners.html

于 2012-06-03T17:38:54.287 回答