Tuesday, May 1, 2012

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)



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


Source: Tips4all

4 comments:

  1. 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.

    ReplyDelete
  2. 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.

    ReplyDelete
  3. + (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;
    }

    ReplyDelete
  4. 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.

    ReplyDelete