views:

241

answers:

3

Let's assume I have the string

NSString* myString  = @"Hello,";

How can I remove the comma without leaving a space? I have tried:

NSString* newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

and

NSString* newString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];

But both are leaving spaces.

+6  A: 

I just ran the following as a test

NSString * myString = @"Hello,";

NSString * newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

NSLog(@"%@xx",newString);

And I get 2010-04-05 18:51:18.885 TestString[6823:a0f] Helloxx as output. There is no space left.

Brandon Bodnár
A: 
NSString *newString = [myString substringToIndex:5];

That will ensure that there are only 5 characters in the string, but beware that this will also throw an exception if there are not at least 5 characters in the string to begin with. How are you handling this string? Is it being displayed to the user? Is it being written to a file? The code that you posted does not reproduce the error, so perhaps you should post the code that you are having a problem with.

dreamlax
A: 

Shouldn't an NSMutableString be used to do something like that?

Bonnie
No, not really.
Chuck
That's one way (`replaceOccurrencesOfString:withString:options:range:`). `stringByReplacingOccurrencesOfString:withString:` and `stringByReplacingOccurrencesOfString:withString:options:range:` are the others.
Peter Hosey