Objective-C removing spaces from strings in an array

I want to import a row-by-row file into an array. I want to get rid of all the spaces before and after the lines so that I can compare the lines a lot easier without having inconsistencies due to the small spaces in the spaces. I have NSData file contents and then take two lines

NSString* string = [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding] autorelease]; NSString* string2 = [[[NSString alloc] initWithBytes:[data2 bytes] length:[data2 length] encoding:NSUTF8StringEncoding] autorelease]; 

I tried to do this to remove the space before adding to the array, but it does not work.

 NSString *newString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; NSString *newString2 = [string2 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; NSArray *fileInput = [newString componentsSeparatedByString:@"\n"]; NSArray *fileInput2 = [newString2 componentsSeparatedByString:@"\n"]; 
+4
source share
3 answers

If you are looking for a replacement for all occurrences of spaces, then using stringByTrimmingCharactersInSet: will not help, since it is only discarded at the beginning and end of the line. You will need to use the stringByReplacingOccurrencesOfString:withString: method to eliminate the spaces.

 NSString * newString = [string stringByReplacingOccurrencesOfString:@" " withString:@""]; NSString * newString2 = [string2 stringByReplacingOccurrencesOfString:@" " withString:@""]; 

but

If you want to trim all rows in an array, you will have to list the array and add the trimmed rows to the new mutable array.

+6
source

Both @Deepak and @Bill Dudney are right, I just throw another way to solve your problem:

 NSMutableArray *fileInput = [NSMutableArray array]; [string enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { if ([line length] > 0) { [fileInput addObject: [line stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; } }]; 

(Disclaimer: Works in iOS 4+, OS X 10.6+ only ... but I love blocks!))

+2
source

It looks like you are removing the empty space in front and back of the whole file, but not from each line. Try something like this:

 NSArray *fileInput2 = [newString2 componentsSeparatedByString:@"\n"]; NSMutableArray *trimmedFileInput2 = [NSMutableArray array]; for(NSString *gak in fileInput2) { [trimmedFileInput2 addObject:[gak stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; } 

[Thanks @Deepak for the comment, dooh!]

+1
source

All Articles