48

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)

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

Matt Sephton
  • 3,711
  • 4
  • 35
  • 46

8 Answers8

122

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.

Nicholas Riley
  • 43,532
  • 6
  • 101
  • 124
27

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.

nikkumang
  • 1,615
  • 2
  • 17
  • 34
  • NSString will not respond to setString. – gotnull Dec 07 '10 at 23:26
  • 2
    right, assuming that `strNew` is an `NSMutableString`. But then if you're going to use NSMutableString, then you might as well do `[strNew replaceOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange(0, [strNew length])]` – user102008 Feb 22 '11 at 04:26
9

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

Tommie C.
  • 12,895
  • 5
  • 82
  • 100
7

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.

Stonz2
  • 6,306
  • 4
  • 44
  • 64
2
+ (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;
}
Josh Brown
  • 52,385
  • 10
  • 54
  • 80
2

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
Matt Sephton
  • 3,711
  • 4
  • 35
  • 46
Michael Peterson
  • 10,383
  • 3
  • 54
  • 51
1

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:"")
Matt Green
  • 185
  • 1
  • 11
1

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.

Gerard
  • 2,832
  • 3
  • 27
  • 39