Best way to split strings into an array Best way to split strings into an array arrays arrays

Best way to split strings into an array


The easiest way to split a NSString into an NSArray is the following:

NSString *string = @"Zakinthos (ZTH),GREECE";NSArray *stringArray = [string componentsSeparatedByString: @","];

This should work for you. Have you tried this?


To expand on hspain's answer, and to bring the solution more in line with the question, i present you with the following

NSString *string = @"Zakinthos (ZTH),GREECE";NSArray *stringArray = [string componentsSeparatedByString: @","];

this gives you a 2 element array: [@"Zakinthos (ZTH)", @"GREECE"];

from here you can easily get the country.

NSString *countryString = stringArray[1]; // GREECE

and repeat the process to refine further:

NSArray *stateArray = [(NSString*)stringArray[0] componentsSeparatedByString:@" "];

stateArray now looks like this [@"Zakinthos", @"(ZTH)"];

NSString *stateString = stateArray[0]; // Zakinthos

and now you have Country and State separated into their own strings, which you can build new arrays with like this:

NSMutableArray *countryArray = [NSMutableArray arrayWithObjects:countryString, nil];NSMutableArray *stateArray = [NSMutableArray arrayWithObjects:stateString, nil];

As you process your document of locations you can add more countries and states to their proper arrays via something like the following:

[countryArray addObject:newCountryString];[stateArray addObject:newStateString];