Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove whitespace from string in Objective-C

I have a couple of strings. Some have a whitespace in the beginning and some not. I want to check if a string begins with a whitespace and if so remove it.

like image 684
Crazer Avatar asked Jan 10 '11 10:01

Crazer


People also ask

How do I remove the white spaces from a string in Objective C?

For those who are trying to remove space in the middle of a string, use [yourString stringByReplacingOccurrencesOfString:@" " withString:@""] .

What is NSString?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

How can remove space from string in IOS?

if You want to remove white spaces at start and end the you use stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet] string method. For eg. NSString *s = @"0800 444 333"; s = [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


Video Answer


1 Answers

There is method for that in NSString class. Check stringByTrimmingCharactersInSet:(NSCharacterSet *)set. You should use [NSCharacterSet whitespaceCharacterSet] as parameter:

NSString *foo = @" untrimmed string "; NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
like image 142
Eimantas Avatar answered Sep 16 '22 16:09

Eimantas