Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C removing whitespace from strings in array

Tags:

objective-c

I want to import a file of strings line by line into an array. I want to get rid of all of the whitespace before and after the strings so that I can compare the strings a lot easier without having them not match due to small whitespace discrepancies. I NSData the content of the files then take the two strings

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 below to remove the whitespace before adding to an array but it does not seem to work.

NSString *newString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSString *newString2 = [string2 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

NSArray *fileInput = [newString componentsSeparatedByString:@"\n"];
NSArray *fileInput2 = [newString2 componentsSeparatedByString:@"\n"];
like image 810
Hillary Franks Avatar asked Feb 23 '23 16:02

Hillary Franks


1 Answers

If you are looking at substituting all occurrences of whitespace then using stringByTrimmingCharactersInSet: won't help as it only trims off at the start and end of the string. You will need to use the stringByReplacingOccurrencesOfString:withString: method to eliminate the whitespace.

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

However,

If you want to trim all the strings in the array then you will have to enumerate the array and add the trimmed strings in a new mutable array.

like image 71
Deepak Danduprolu Avatar answered Mar 06 '23 17:03

Deepak Danduprolu