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

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

NSString will not respond to setString.
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])]
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

Comments

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.

Comments

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

Comments

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

Comments

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.

Comments

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:"")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.