views:

147

answers:

3

Is there any function to remove the white spaces from text message in objective c?

For eg:for "How are you",the result should be "howareyou"

Thanks in advance.

+1  A: 

You could use NSString's componentsSeparatedByCharactersInSet with whitespaceCharacterSet to first split the string on the whitespace, and then join the components using NSArray's componentsJoinedByString.

eg.

NSString *myString=@"How are you";
myString = [[myString componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString: @""];
NSLog(myString); // displays Howareyou
Tom
Thanks Tom, it worked :)
Iya
+1  A: 

Tom's approach isn't very efficient. What you want is:

-stringByTrimmingCharactersInSet:
NSResponder
Which only removes characters from either end of the string, not all white spaces in the string, which is what the original question was about. That said if trimming the white space from the ends of the string is what you're after this is the correct way to do it.
Tom
Oops, I didn't remember correctly what -stringByTrimmingCharactersInSet: did.
NSResponder
A: 
NSString *myString = @"How are you";
myString = [myString stringByReplacingOccurrencesOfString:@" " withString:@""];
Adolfo