Remove whitespace from string in Objective-C

Objective CStringWhitespace

Objective C Problem Overview


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.

Objective C Solutions


Solution 1 - Objective C

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]];

Solution 2 - Objective C

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

NSString *testString = @"  Eek! There are leading and trailing spaces  ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
                             [NSCharacterSet whitespaceAndNewlineCharacterSet]];

Solution 3 - Objective C

This will remove only the leading white 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

Solution 4 - Objective C

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

Step 1: Edit your app's PCH file, this should be named Project-Name-Prefix.pch

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

Step 2: Enjoy writing way less code when you want to trim a string

NSLog(@"Output: %@ %@", TRIM(@"Hello        "), TRIM(@"World      "));

Output: Hello World

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCrazerView Question on Stackoverflow
Solution 1 - Objective CEimantasView Answer on Stackoverflow
Solution 2 - Objective CJohn ParkerView Answer on Stackoverflow
Solution 3 - Objective CRyan HeitnerView Answer on Stackoverflow
Solution 4 - Objective Cuser511037View Answer on Stackoverflow