Remove space from string in Objective-C

I have a couple of lines. Some have a space at the beginning, and some do not. I want to check if a line starts with a space, and if so remove it.

+63
string objective-c whitespace
Jan 10 '11 at 10:17
source share
4 answers

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

 NSString *foo = @" untrimmed string "; NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
+191
Jan 10 '11 at 10:21
source share

You can use the stringByTrimmingCharactersInSet NSString method with whitespaceAndNewlineCharacterSet NSCharacterSet as such:

 NSString *testString = @" Eek! There are leading and trailing spaces "; NSString *trimmedString = [testString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
+65
Jan 10 '11 at 10:21
source share

This will remove only the leading space.

 NSString *myString = @" 123 "; NSLog(@"mystring %@, length %d",myString, myString.length); NSRange range = [myString rangeOfString:@"^\\s*" options:NSRegularExpressionSearch]; myString = [myString stringByReplacingCharactersInRange:range withString:@""]; NSLog(@"mystring %@, length %d",myString, myString.length); 

output

 mystring 123 , length 9 mystring 123 , length 6 
+5
Jul 19 '13 at 7:09
source share

I wrote a quick macro to reduce the amount of code that needs to be written.

Step 1: edit the PCH file of the application, it should be called Project-Name-Prefix.pch

 #define TRIM(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] 

Step 2. Enjoy writing less code if you want to trim a line.

 NSLog(@"Output: %@ %@", TRIM(@"Hello "), TRIM(@"World ")); Output: Hello World 
+5
May 04 '14 at 3:34
source share



All Articles