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. 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
Both dasblinkenlight’s and Matthias’s answers will work, but they both result in the creation of a couple of intermediate NSStrings; 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.
The simplest solution is running stringByReplacingOccurrencesOfString
twice:
NSString *string = [[myString
stringByReplacingOccurrencesOfString:@"<wow>" withString:someString1]
stringByReplacingOccurrencesOfString:@"<boo>" withString:someString2];
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With