Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

like image 958
s6luwJ0A3I Avatar asked Nov 17 '12 17:11

s6luwJ0A3I


4 Answers

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.

like image 98
Noah Witherspoon Avatar answered Nov 20 '22 14:11

Noah Witherspoon


The simplest solution is running stringByReplacingOccurrencesOfString twice:

NSString *string  = [[myString
    stringByReplacingOccurrencesOfString:@"<wow>" withString:someString1]
    stringByReplacingOccurrencesOfString:@"<boo>" withString:someString2];
like image 26
Sergey Kalinichenko Avatar answered Nov 20 '22 14:11

Sergey Kalinichenko


I would just run the string replacing method again

NSString *string  = [myString stringByReplacingOccurrencesOfString:@"foo" withString:@"String 1"];
string = [string stringByReplacingOccurrencesOfString:@"bar" withString:@"String 2"];
like image 30
Matthias Bauch Avatar answered Nov 20 '22 15:11

Matthias Bauch


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
like image 2
Prashant Gaikwad Avatar answered Nov 20 '22 14:11

Prashant Gaikwad