Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove leading & trailing whitespace of NSString inside an NSArray?

I have an NSArray declared as such:

@property (nonatomic, strong) NSArray *arrayRefineSubjectCode; 

I have the array elements manually filled out as below:

     arrayRefineSubjectCode = [NSArray arrayWithObjects:                               @"  BKKC 2061",                               @"   BKKS 2631   ",                               @"BKKS 2381      ",                               nil]; 

So how do I remove starting and ending whitespace and make each array elements to become as these:

     arrayRefineSubjectCode = [NSArray arrayWithObjects:                               @"BKKC 2061",                               @"BKKS 2631",                               @"BKKS 2381",                               nil]; 

I have tried using "stringByTrimmingCharactersInSet:" but it only works for NSString. Kinda confused here. Please help...

like image 714
shamsulfakhar Avatar asked Feb 15 '12 10:02

shamsulfakhar


People also ask

How do you get rid of leading and trailing spaces?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.


1 Answers

The NSArray and the contained NSString objects are all immutable. There's no way to change the objects you have.

Instead you have to create new strings and put them in a new array:

NSMutableArray *trimmedStrings = [NSMutableArray array]; for (NSString *string in arrayRefineSubjectCode) {     NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];     [trimmedStrings addObject:trimmedString]; } arrayRefineSubjectCode = trimmedStrings; 
like image 188
Nikolai Ruhe Avatar answered Oct 09 '22 13:10

Nikolai Ruhe