Reputation: 10039
I am an iOS newbie, so please pardon me if this is a beginner level question.
I have a string "hu_HU Hungary:Hungarian" and I want to put it into an array like {"hu", "HU", "Hungary:Hungarian"}. How would I parse it to remove the whitespace and then the underscore?
Upvotes: 0
Views: 1512
Reputation: 655
All of these answers share an annoying problem. They assume that the items are separated by one and only one space.
NSString *theStr = @"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
NSString *theStr = @"hu_HU Hungary:Hungarian"; // note extra space
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", " ", "Hungary:Hungarian"}
Upvotes: 0
Reputation: 3191
Here you are:
NSString *myString = @"hu_HU Hungary:Hungarian";
myString = [myString stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSArray *myArray = [myString componentsSeparatedByString:@" "];
Upvotes: 0
Reputation: 22633
NSString *theStr = @"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
pieces = [theStr componentsSeparatedByCharactersInSet: [[NSCharacterSet alphanumericCharacterSet] invertedSet]];
//pieces = {"hu", "HU", "Hungary", "Hungarian"}
//the motivation for this is a better defined set of non-alphanumeric characters
Upvotes: 0
Reputation: 27147
To get the desired effect you must change the '_' to a ' ' or vice versa. Then you can use componentsSeparatedByString, like so:
NSString *source = @"hu_HU Hungary:Hungarian";
source = [source stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSArray *components = [source componentsSeparatedByString:@" "];
NSLog(@"%@",components);
Upvotes: 0