Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing multiple spaces in NSString

I have a NSString, this has multiple spaces, I want to trim those spaces and make a single space for e.g.@"how.....are.......you" into @"how are you".(dots are simply spaces)

I have tried with

NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

It not seems to work. Any idea.

like image 631
Newbee Avatar asked Aug 27 '12 06:08

Newbee


3 Answers

You could use a regular expression to accomplish this:

NSError *error = nil;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"  +" options:NSRegularExpressionCaseInsensitive error:&error];

The pattern is a space followed by one or more occurrences of space. Replace this with a single space in your string:

NSString *trimmedString = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [user_ids length]) withTemplate:@" "];
like image 119
MadhavanRP Avatar answered Oct 21 '22 16:10

MadhavanRP


This worked when I tried it:

NSString *trimmedString = @"THIS      IS      A     TEST S    STRING   S D        D F ";
    while ([trimmedString rangeOfString:@"  "].location != NSNotFound) {
        trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"  " withString:@" "];
    }
NSLog(@"%@", trimmedString);
like image 24
WolfLink Avatar answered Oct 21 '22 16:10

WolfLink


user1587011

NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

this string method used to remove spaces at begining and last of a string.

Try this it gives you what you want:--

NSString *theString = @"    Hello      this  is a   long       string!   ";

NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];

NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:@" "];
like image 11
Ravi Sharma Avatar answered Oct 21 '22 16:10

Ravi Sharma