Tuesday, January 12, 2016

Objective C trimming NSString

Trimming a string plays a major role while validating your forms like registration, user profile etc in iOS applications. Before validating a registration form, where user enters his/her details, we need to trim especially white space characters along with restricted characters. Because there is a chance that users enters white space character by clicking space at the beginning or at the end of a string by mistake. 

End of the day it's developer's responsibility to remove those before validation and alerting the user as they will definitely hesitate to go back to each and every field of your form and remove these white space characters on their own which is bit hectic to them on their device.

Let's see how we can do that in Objective c.

There is a simple method in NSString to do this trimming of white space characters.

      NSString *firstname = [firstnameTF.text stringByTrimmingCharactersInSet
                                                                   [NSCharacterSet whitespaceCharacterSet]];

This simple line of statement eliminates white spaces at both ends of a string. 

This is a good practice here, whereas it becomes mandatory if there is a search filed and we need to display the items containing user entered search string. If there are white spaces in the search string and If we don't trim that string, user's will definitely get wrong data and will get disappointed by the search results and in the end of the day our app will get blamed. That's how this trimming a string becomes mandatory in the search functionality.

      NSString *searchString = [searchField.text stringByTrimmingCharactersInSet
                                                                    [NSCharacterSet whitespaceCharacterSet]];

It's a good practice to do this for all entry fields to avoid these wrong results. Not only white spaces, we can also trim different character sets based on our requirement.

Here are some character sets for your quick reference.

+ (NSCharacterSet *)controlCharacterSet;
+ (NSCharacterSet *)whitespaceCharacterSet;
+ (NSCharacterSet *)whitespaceAndNewlineCharacterSet;
+ (NSCharacterSet *)decimalDigitCharacterSet;
+ (NSCharacterSet *)letterCharacterSet;
+ (NSCharacterSet *)lowercaseLetterCharacterSet;
+ (NSCharacterSet *)uppercaseLetterCharacterSet;
+ (NSCharacterSet *)nonBaseCharacterSet;
+ (NSCharacterSet *)alphanumericCharacterSet;
+ (NSCharacterSet *)decomposableCharacterSet;
+ (NSCharacterSet *)illegalCharacterSet;
+ (NSCharacterSet *)punctuationCharacterSet;
+ (NSCharacterSet *)capitalizedLetterCharacterSet;
+ (NSCharacterSet *)symbolCharacterSet;
+ (NSCharacterSet *)newlineCharacterSet NS_AVAILABLE(10_5, 2_0);

Hope this post is useful. Feel free to comment incase of any queries.