user4444009
user4444009

Reputation:

replace multiple characters in nsstring with other multiple characters

replace multiple characters in nsstring with other multiple characters?

NSString *jobs = @"The designs of the iPhone 6 and iPhone 6 Plus were influenced by that of the iPad Air, with a glass front that is curved around the edges of the display,and an aluminum rear that contains two plastic strips for the antenna; both models come in gold, silver, and space gray finishes";


NSString * jobs2 = [jobs stringByReplacingOccurrencesOfString:@" "withString:@"_"];

NSLog(@" string is %@ ",jobs2);

it replace space(" ") to "-"

but i want a replace with @ s replace with $ h replace with #,,etc

all in single function to replace multiple characters in nsstring with other multiple characters?

Upvotes: 0

Views: 787

Answers (2)

mttcrsp
mttcrsp

Reputation: 1651

This method accepts a string and a dictionary. The string is the original string in which you want to replace various characters, the second one is a dictionary containing the characters you want to replace as the keys and the new characters you want to insert as the values.

- (NSString *)replaceSubstringsIn:(NSString *)string with:(NSDictionary *)replacements {

    NSString *result = string;

    for (NSString *key in replacements) {
        result = [result stringByReplacingOccurrencesOfString:key
                                                   withString:replacements[key]];
    }

    return result;
}

You can call it like this

NSDictionary *dictionary = @{ @" " : @"-", @"some" : @"any"};
NSString *string = @"some to any";

NSLog(@"%@", [self replaceSubstringsIn:string with:dictionary]);

Upvotes: 1

air_bob
air_bob

Reputation: 1337

write a dictionary contains the replace characters and write your own function to iterate the character replacement(then wrap it in a NSString category) Or enumerate and replace them.

Refer to this sof post: https://stackoverflow.com/a/19314718/874585

Upvotes: 0

Related Questions