Replace multiple characters in a string in Objective-C?

In PHP, I can do this:

$new = str_replace(array('/', ':', '.'), '', $new); 

... replace all instances of /: characters. with an empty string (to remove them)

Can I do this easily in Objective-C? Or do I need to roll on my own?

I am currently stringByReplacingOccurrencesOfString several calls to stringByReplacingOccurrencesOfString :

 strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""]; strNew = [strNew stringByReplacingOccurrencesOfString:@":" withString:@""]; strNew = [strNew stringByReplacingOccurrencesOfString:@"." withString:@""]; 

Thank,
matte

+45
string replace objective-c iphone
Apr 3 '09 at 13:32
source share
8 answers

A somewhat inefficient way to do this:

 NSString *s = @"foo/bar:baz.foo"; NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."]; s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; NSLog(@"%@", s); // => foobarbazfoo 

Take a look at NSScanner and -[NSString rangeOfCharacterFromSet: ...] if you want to do this more efficiently.

+116
Apr 03 '09 at 13:55
source share

There are situations when your method is good enough, I think matte. By the way, I think it's better to use

 [strNew setString: [strNew stringByReplacingOccurrencesOfString:@":" withString:@""]]; 

but not

 strNew = [strNew stringByReplacingOccurrencesOfString:@"/" withString:@""]; 

since I think you are overwriting the NSMutableString pointer with NSString, which could cause a memory leak.

+27
Jun 02 '09 at 14:01
source share

Essentially the same as Nicholas above, but if you want to delete everything, EXCLUDE the character set (say you want to delete everything that is not in the set "ABCabc123"), you can do the following:

 NSString *s = @"A567B$%C^.123456abcdefg"; NSCharacterSet *doNotWant = [[NSCharacterSet characterSetWithCharactersInString:@"ABCabc123"] invertedSet]; s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; NSLog(@"%@", s); // => ABC123abc 

Useful for deleting characters, etc. if you only need alphanumeric.

+5
Jan 22 '14 at 16:34
source share

I had to do this recently and wanted to use an effective method:

(assuming someText is an NSString or text attribute)

 NSString* someText = @"1232342jfahadfskdasfkjvas12!"; 

(in this example, lines from line will be broken)

 [someText stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [someText length])]; 

Keep in mind that you need to escape the regex character using the Obj-c escape character:

(obj-c uses double backslashes to avoid special regular expressions)

 ...stringByReplacingOccurrencesOfString:@"[\\\!\\.:\\/]" 

What makes it interesting is that the NSRegularExpressionSearch option is not used much, but can lead to some very powerful controls:

You can find the iOS regex tutorial here and more on regex at regex101.com

+5
Sep 06 '14 at 10:15
source share
 + (NSString*) decodeHtmlUnicodeCharactersToString:(NSString*)str { NSMutableString* string = [[NSMutableString alloc] initWithString:str]; // #&39; replace with ' NSString* unicodeStr = nil; NSString* replaceStr = nil; int counter = -1; for(int i = 0; i < [string length]; ++i) { unichar char1 = [string characterAtIndex:i]; for (int k = i + 1; k < [string length] - 1; ++k) { unichar char2 = [string characterAtIndex:k]; if (char1 == '&' && char2 == '#' ) { ++counter; unicodeStr = [string substringWithRange:NSMakeRange(i + 2 , 2)]; // read integer value ie, 39 replaceStr = [string substringWithRange:NSMakeRange (i, 5)]; // #&39; [string replaceCharactersInRange: [string rangeOfString:replaceStr] withString:[NSString stringWithFormat:@"%c",[unicodeStr intValue]]]; break; } } } [string autorelease]; if (counter > 1) return [self decodeHtmlUnicodeCharactersToString:string]; else return string; } 
+2
Apr 01 '10 at
source share

If the characters you want to delete must be adjacent to each other, you can use

 stringByReplacingCharactersInRange:(NSRange) withString:(NSString *) 

In addition, I think that using the same function several times is not so bad. This is much more readable than creating a large method in order to do the same in a more general way.

+1
Jan 18 2018-12-18T00:
source share

Here is an example in Swift 3 using the regex option to replace Save.

Use replaceOccurrences with the String.CompareOptions.regularExpression option.

Example (Swift 3):

 var x = "<Hello, [play^ground+]>" let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil) print(y) 

Output:

 7Hello, 7play7ground777 
+1
Nov 10 '16 at 15:36
source share

Create an extension on String ...

 extension String { func replacingOccurrences(of strings:[String], with replacement:String) -> String { var newString = self for string in strings { newString = newString.replacingOccurrences(of: string, with: replacement) } return newString } } 

Name it as follows:

 aString = aString.replacingOccurrences(of:['/', ':', '.'], with:"") 
+1
Nov 18 '16 at 13:41
source share



All Articles