Alex Rivera | Logout

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

Asked 2012-02-15T10:27:44.530
44

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...

Edit
Report

1 Answer

83

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;
answered 2012-02-15T10:32:28.327

Your Answer