2010-08-30 107 views
3

我想在Objective-C中的字符串中替换多个元素。在不过Objective-C字符串替换

str_replace(array("itemtoreplace", "anotheritemtoreplace", "yetanotheritemtoreplace"), "replacedValue", $string); 

的Objective-C,我知道的唯一方法就是NSString的replaceOccurancesOfString:

在PHP中,你可以做到这一点。有没有任何有效的方法来取代多个字符串?

这是我目前的解决方案(非常低效和..嗯......长)

NSString *newTitle = [[[itemTitleField.text stringByReplacingOccurrencesOfString:@"'" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@"'"] stringByReplacingOccurrencesOfString:@"^" withString:@""]; 

明白我的意思吗?

感谢, 基督教斯图尔特

+0

有没有相当于对象 - 即PHP方法。试着打破你的方法调用三行,所以我们可以看到发生崩溃的确切位置。 – kubi 2010-08-30 01:24:05

+0

Kubi,谢谢你的回答。这并不是真正的困扰我的崩溃。它是整个交易的低效率(如果这是一个字)。 谢谢! Christian – 2010-08-30 01:28:04

回答

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 

输出:

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? 
+0

嘿理查!惊人!我见过的最详细的消息。 只是问 - 输出是什么?你是怎么得到这个的?看起来完全像控制台中的合法输出 - 我的意思是 - a0f?你测试过了吗? 非常感谢! – 2010-08-30 02:17:07

+0

输出是在调用“方法”之后,NSLog(@“%@”,originalString); – Richard 2010-08-30 02:25:44

+0

我们是否必须发布创建的临时字符串? – gav 2013-01-24 19:51:34

-2

添加@给所有字符串的开始,在

withString:@"" 

它遗漏了几个。

+0

这只是我在这里输入的问题。我修好了它。你知道一个有效的方法来做到这一点?非常感谢。 – 2010-08-30 01:27:29

0

考虑编写自己的方法?对字符串进行Tokenize并逐个替换它们,实际上没有比用O(n)替换字符串中的单词更快的方法。

最多只有一个循环。

+0

也是一个很好的答案。非常感谢:D – 2010-08-30 01:52:29

2

有没有更紧凑的方式来写这与可可框架。从代码角度来看,它可能看起来效率低下,但实际上这种事情可能不会经常出现,除非您的输入非常大,而且您经常这样做,否则您不会因此而受到影响。考虑将它们分别写在三行上,以便进行可读性和链接。

如果你正在做一些关键性能要求批量替换的东西,你总是可以编写自己的函数。这甚至会是一个有趣的面试问题。 :)

+0

伟大的综合答案。我认为我现在就去解决这个问题 - 我可能会回复您关于自定义功能的信息:D。 – 2010-08-30 01:53:04