user523234
user523234

Reputation: 14834

Remove white spaces between words in a string but one

Here is the snippet will explain it. Basically, I want to remove all empty spaces between two words except one. Are there any simpler stock methods to do this?

NSString *originalString = @"one two  three    four        five";
NSArray *stringArray = [originalString componentsSeparatedByString:@" "];
NSPredicate *whiteSpacePredicate = [NSPredicate predicateWithFormat:@"SELF != ''"];
NSArray *stringArray2 = [stringArray filteredArrayUsingPredicate:whiteSpacePredicate];
NSString *newString = @"";
for (NSString *string in stringArray2)
{
    newString = [[newString stringByAppendingString:string] stringByAppendingString:@" "];
}
NSLog(@"originalString: %@", originalString);
NSLog(@"newString: %@", newString);

Upvotes: 0

Views: 473

Answers (1)

Cihan Tek
Cihan Tek

Reputation: 5409

You can do something like this

NSString *newString= [originalString stringByReplacingOccurrencesOfString: @"[ \t]+"
                                                             withString: @" "
                                                                options: NSRegularExpressionSearch
                                                                  range: NSMakeRange(0, originalString.length)];

which will remove all extra space and tab characters from the original String.

Upvotes: 6

Related Questions