Chr*_*art 3 string replace objective-c
我想在Objective-C中替换我的字符串中的多个元素.
在PHP中,您可以这样做:
str_replace(array("itemtoreplace", "anotheritemtoreplace", "yetanotheritemtoreplace"), "replacedValue", $string);
Run Code Online (Sandbox Code Playgroud)
但是在objective-c中,我所知道的唯一方法是NSString replaceOccurancesOfString.有没有有效的方法来替换多个字符串?
这是我目前的解决方案(非常低效且......好......长)
NSString *newTitle = [[[itemTitleField.text stringByReplacingOccurrencesOfString:@"'" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@"'"] stringByReplacingOccurrencesOfString:@"^" withString:@""];
Run Code Online (Sandbox Code Playgroud)
明白了吗?
谢谢,Christian Stewart
Ric*_*ard 12
如果这是你在这个程序或其他程序中经常要做的事情,可能会创建一个方法或条件循环来传递原始字符串,并使用多维数组来保存字符串以查找/替换.可能不是最有效的,但是这样的事情:
// Original String
NSString *originalString = @"My^ mother^ told me not to go' outside' to' play today. Why did I not listen to her?";
// Method Start
// MutableArray of String-pairs Arrays
NSMutableArray *arrayOfStringsToReplace = [NSMutableArray arrayWithObjects:
[NSArray arrayWithObjects:@"'",@"",nil],
[NSArray arrayWithObjects:@" ",@"'",nil],
[NSArray arrayWithObjects:@"^",@"",nil],
nil];
// For or while loop to Find and Replace strings
while ([arrayOfStringsToReplace count] >= 1) {
originalString = [originalString stringByReplacingOccurrencesOfString:[[arrayOfStringsToReplace objectAtIndex:0] objectAtIndex:0]
withString:[[arrayOfStringsToReplace objectAtIndex:0] objectAtIndex:1]];
[arrayOfStringsToReplace removeObjectAtIndex:0];
}
// Method End
Run Code Online (Sandbox Code Playgroud)
输出:
2010-08-29 19:03:15.127 StackOverflow[1214:a0f] My'mother'told'me'not'to'go'outside'to'play'today.'Why'did'I'not'listen'to'her?
Run Code Online (Sandbox Code Playgroud)