views:

6186

answers:

3

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

+4  A: 

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
Thanks for the answer, will do
matt
+4  A: 

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.

NiKUMAN
Thanks Nick - always good to hear about the small details
matt
A: 
  • (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; }**



**

Krishna Gupta
Please format your comment with code tags
matt