[英]How to replace occurrences of multiple strings with multiple other strings [NSString]
NSString *string = [myString stringByReplacingOccurrencesOfString:@"<wow>" withString:someString];
我有这个代码。 现在,假设我的应用程序的用户输入了两个我想用其他两个不同的字符串替换的字符串,我该如何实现? 我不在乎它是否使用私有API,我正在为越狱平台开发程序。 我的用户要输入或或。 我想用它们各自要替换的字符串替换那些字符串的出现:)
在此先感谢:P
最简单的解决方案是运行stringByReplacingOccurrencesOfString
两次:
NSString *string = [[myString
stringByReplacingOccurrencesOfString:@"<wow>" withString:someString1]
stringByReplacingOccurrencesOfString:@"<boo>" withString:someString2];
dasblinkenlight和Matthias的答案都可以使用,但是它们都导致创建了两个中间NSString。 如果您不经常执行此操作,这并不是真正的问题,但是更好的方法如下所示。
NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:@"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:@"b" withString:somethingElseElse];
// etc.
然后,您可以像使用myStringMut
一样使用myString
,因为NSMutableString是NSString子类。
我将再次运行字符串替换方法
NSString *string = [myString stringByReplacingOccurrencesOfString:@"foo" withString:@"String 1"];
string = [string stringByReplacingOccurrencesOfString:@"bar" withString:@"String 2"];
这在Swift 3.1中对我来说效果很好
let str = "hi hello hey"
var replacedStr = (str as NSString).replacingOccurrences(of: "hi", with: "Hi")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hello", with: "Hello")
replacedStr = (replacedStr as NSString).replacingOccurrences(of: "hey", with: "Hey")
print(replacedStr) // Hi Hello Hey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.