String replacement in Objective-C
264,384
Solution 1
You could use the method
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
...to get a new string with a substring replaced (See NSString
documentation for others)
Example use
NSString *str = @"This is a string";
str = [str stringByReplacingOccurrencesOfString:@"string"
withString:@"duck"];
Solution 2
NSString
objects are immutable (they can't be changed), but there is a mutable subclass, NSMutableString
, that gives you several methods for replacing characters within a string. It's probably your best bet.
Solution 3
If you want multiple string replacement:
NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo
Solution 4
It also posible string replacement with stringByReplacingCharactersInRange:withString:
for (int i = 0; i < card.length - 4; i++) {
if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) {
NSRange range = NSMakeRange(i, 1);
card = [card stringByReplacingCharactersInRange:range withString:@"*"];
}
} //out: **** **** **** 1234
Related videos on Youtube
Author by
4thSpace
Updated on May 10, 2020Comments
-
4thSpace almost 4 years
How to replace a character is a string in Objective-C?
-
ele about 11 yearsI thought the point of having NSString and an NSMutableString subclass was because an instance of NSString is unchangeable. While--like any sane person, I'd rather have ducks than strings any day--the fact that you just overwrote the contents of
str
just blew my mind. -
Colas about 11 yearsBut I guess the adress of
str
changed in the process -
Septiadi Agus almost 11 yearsit doesn't change. str now contains a whole new string. stringByReplacingOccurencesOfString does NOT mutate the string. It simply return a new string.
-
Jed Fox almost 7 yearsPlease use the edit link to explain how this code works and don't just give the code, as an explanation is more likely to help future readers. See also How to Answer. source