views:

47

answers:

3

Hi,

I would like to reduce the number of spaces between two words in a NSString (Objective-C/iPhone dev) to only one. Do you know some method that could do that ?

Exemple :

Before cleaning : "Hi,       my   name       is                Tom."
After cleaning : "Hi, my name is Tom."

Thanks

+1  A: 

Take a look at http://regexkit.sourceforge.net/, it has NSString extensions with which you could do regex-based string replace.

The MYYN
+2  A: 

Use [mystring componentsSeparatedByString:@" "] to get a NSArray of all substrings separated by a single space. Then, recombine the non-empty strings in the array to get the final string.

Jim
Thanks, I think this the simplier way to get what I want ;)
Yoot
A: 

using RegexKit, adding to RSC's answer

NSString *subjectString     = @"Hi,       my   name       is                Tom.";
NSString *regexString       = @"(\\s+)";
NSString *replacementString = @" ";

NSString *newString = [subjectString stringByMatching:regexString replace:RKReplaceAll withString:replacementString];
slf