Reputation: 14834
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
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