创建一个NSString的集合/数组以与stringByReplacingOccurrencesOfString一起使用

时间:2016-02-03 20:06:31

标签: ios objective-c replace nsstring

我想用特定的字符串替换NSString中的某些类似字词。例如:

stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"Hello" withString:@"Top o' de marnin ter yer"];
stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"hello" withString:@"Top o' de marnin ter yer"];
stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"Hey" withString:@"Top o' de marnin ter yer"];
stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"hey" withString:@"Top o' de marnin ter yer"];
stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"Hi" withString:@"Top o' de marnin ter yer"];
stringToChange = [stringToChange stringByReplacingOccurrencesOfString:@"hi" withString:@"Top o' de marnin ter yer"];

这显然不是很有效,而且我很难找到解决方案。

是否可以将这些NSString放入数组或某种字符串集中,因此生成的代码看起来更像:

stringToChange = [stringToChange stringByReplacingOccurrencesOfString:arrayOfStrings withString:@"Top o' de marnin ter yer"];

arrayOfStrings包含@"Hello", @"hello", @"Hey", @"hey", @"Hi", @"hi"的位置。

1 个答案:

答案 0 :(得分:2)

您当然可以将搜索字符串放入集合中,循环遍历集合,然后对循环的每个步骤执行搜索和替换。但这也是搜索列表中每个项目的字符串循环。

相反,您应该使用NSScanner,在找到匹配项时移动字符串。对于较长的源字符串,您会发现 far 在时间和空间上都更有效。使用stringByReplacingOccurrencesOfString:withString:每次都会创建一个新字符串;您当然可以通过首先转换为NSMutableString并使用replaceOccurrencesOfString:withString:options:range:

来改善这种情况

以下是扫描仪的使用方法:

NSScanner * scanner = [NSScanner scannerWithString:source];
NSMutableString * fixedUpString = [NSMutableString string];

NSArray * searchStrings = @[/* The items you want to remove */];
NSString * replacementString = /* The new material */;

while( ![scanner isAtEnd] ){

    // Moving through the string, try each search in turn
    for( NSString * searchString in searchStrings ){

        // If there's a match, save what's been scanned up to that point
        NSString * scanned;
        if( [scanner scanUpToString:searchString intoString:&scanned] ){

            [fixedUpString appendString:scanned];
            // and add the new material
            [fixedUpString appendString:replacementString];
            // Move past the searched piece and continue
            [scanner scanString:searchString intoString:NULL];
        }
    }
}

fixedUpString现在包含原始字符串中的所有内容,并替换了目标短语。