Replace multiple characters in a string in Objective-C?

In PHP I can do this:

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

…to replace all instances of the characters / : . with a blank string (to remove them)

  • How to toggle visibility of NSSplitView subView + hide Pane Splitter divider?
  • UISearchBar on the top of UITableView which can hide but stay close to UINavigationBar
  • Xcode No Choice of Devices in Deployment Info Section of Universal App
  • Callback Method if user declines Push Notification Prompt?
  • When assigning focus via becomeFirstResponder to UISearchController's UISearchBar, the keyboard does not appear
  • Change the Width of UISearchBars on a TableView
  • Can I do this easily in Objective-C? Or do I have to roll my own?

    Currently I am doing multiple calls to stringByReplacingOccurrencesOfString:

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

    Thanks,
    matt

    8 Solutions Collect From Internet About “Replace multiple characters in a string in Objective-C?”

    A somewhat inefficient way of doing this:

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

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

    There are situations where your method is good enough I think matt.. BTW, I think it’s better to use

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

    rather than

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

    as I think you’re overwriting an NSMutableString pointer with an NSString which might cause a memory leak.

    Essentially the same thing as Nicholas posted above, but if you want to remove everything EXCEPT a set of characters (say you want to remove everything that isn’t in the set “ABCabc123”) then 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 in stripping out symbols and such, if you only want alphanumeric.

    Had to do this recently and wanted to share an efficient method:

    (assuming someText is a NSString or text attribute)

    NSString* someText = @"1232342jfahadfskdasfkjvas12!";
    

    (this example will strip numbers from a string)

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

    Keep in mind that you will need to escape regex literal characters using Obj-c escape character:

    (obj-c uses a double backslash to escape special regex literals)

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

    What makes this interesting is that NSRegularExpressionSearch option is little used but can lead to some very powerful controls:

    You can find a nice iOS regex tutorial here and more on regular expressions at regex101.com

    + (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 i.e, 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;
    }
    

    If the characters you wish to remove were to be adjacent to each other you could use the

    stringByReplacingCharactersInRange:(NSRange) withString:(NSString *)
    

    Other than that, I think just using the same function several times isn’t that bad. It is much more readable than creating a big method to do the same in a more generic way.

    Here is an example in Swift 3 using the regularExpression option of replacingOccurances.

    Use replacingOccurrences along with a 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
    

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

    Call it like this:

    aString = aString.replacingOccurrences(of:['/', ':', '.'], with:"")