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"];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With