加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Objective-C String-Replace

发布时间:2020-12-16 10:17:33 所属栏目:百科 来源:网络整理
导读:我想在Objective-C中替换我的字符串中的多个元素. 在PHP中,您可以这样做: str_replace(array("itemtoreplace","anotheritemtoreplace","yetanotheritemtoreplace"),"replacedValue",$string); 但是在objective-c中,我所知道的唯一方法是NSString replaceOcc
我想在Objective-C中替换我的字符串中的多个元素.

在PHP中,您可以这样做:

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

但是在objective-c中,我所知道的唯一方法是NSString replaceOccurancesOfString.有没有有效的方法来替换多个字符串?

这是我目前的解决方案(非常低效且……好……长)

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

明白了吗?

谢谢,
Christian Stewart

解决方法

如果这是你在这个程序或其他程序中经常要做的事情,可能会创建一个方法或条件循环来传递原始字符串,并使用多维数组来保存字符串以查找/替换.可能不是最有效的,但是这样的事情:

// 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:@" ",@"'",[NSArray arrayWithObjects:@"^",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?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读