简体   繁体   English

如何用多个其他字符串替换多个字符串的出现[NSString]

[英]How to replace occurrences of multiple strings with multiple other strings [NSString]

NSString *string  = [myString stringByReplacingOccurrencesOfString:@"<wow>" withString:someString];

I have this code. 我有这个代码。 Now suppose my app's user enters two different strings I want to replace with two different other strings, how do I achieve that? 现在,假设我的应用程序的用户输入了两个我想用其他两个不同的字符串替换的字符串,我该如何实现? I don't care if it uses private APIs, i'm developing for the jailbroken platform. 我不在乎它是否使用私有API,我正在为越狱平台开发程序。 My user is going to either enter or or . 我的用户要输入或或。 I want to replace any occurrences of those strings with their respective to-be-replaced-with strings :) 我想用它们各自要替换的字符串替换那些字符串的出现:)

Thanks in advance :P 在此先感谢:P

The simplest solution is running stringByReplacingOccurrencesOfString twice: 最简单的解决方案是运行stringByReplacingOccurrencesOfString两次:

NSString *string  = [[myString
    stringByReplacingOccurrencesOfString:@"<wow>" withString:someString1]
    stringByReplacingOccurrencesOfString:@"<boo>" withString:someString2];

Both dasblinkenlight's and Matthias's answers will work, but they both result in the creation of a couple of intermediate NSStrings; dasblinkenlight和Matthias的答案都可以使用,但是它们都导致创建了两个中间NSString。 that's not really a problem if you're not doing this operation often, but a better approach would look like this. 如果您不经常执行此操作,这并不是真正的问题,但是更好的方法如下所示。

NSMutableString *myStringMut = [[myString mutableCopy] autorelease];
[myStringMut replaceOccurrencesOfString:@"a" withString:somethingElse];
[myStringMut replaceOccurrencesOfString:@"b" withString:somethingElseElse];
// etc.

You can then use myStringMut as you would've used myString , since NSMutableString is an NSString subclass. 然后,您可以像使用myStringMut一样使用myString ,因为NSMutableString是NSString子类。

I would just run the string replacing method again 我将再次运行字符串替换方法

NSString *string  = [myString stringByReplacingOccurrencesOfString:@"foo" withString:@"String 1"];
string = [string stringByReplacingOccurrencesOfString:@"bar" withString:@"String 2"];

This works well for me in Swift 3.1 这在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM