Suchi
Suchi

Reputation: 10039

iOS - parse a string using whitespace

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

Answers (5)

Michelle Six
Michelle Six

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

Andrew Zimmer
Andrew Zimmer

Reputation: 3191

Here you are:

NSString *myString = @"hu_HU Hungary:Hungarian";
myString = [myString stringByReplacingOccurrencesOfString:@"_" withString:@" "];
NSArray *myArray = [myString componentsSeparatedByString:@" "];

Upvotes: 0

Patrick Perini
Patrick Perini

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

NJones
NJones

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

Vitaly S.
Vitaly S.

Reputation: 2389

Use componentsSeparatedByCharactersInSet: method of NSString

Upvotes: 2

Related Questions