25

I'm developing a travel app, I have to read a txt file that contains all the states and countries, as you can notice this is a pretty huge file to read, anyway, this is an example of the text inside the file:

Zakinthos (ZTH),GREECE
Zanesville (ZZV),USA
Zanjan (JWN),IRAN
Zanzibar (ZNZ),TANZANIA
...

Now i'm reading the file with no problem but I don't know how to create two arrays, one with the state and another with the country so I can show them into a table when text is being autocompleted.

I've tried using NSScanner using the "," as a delimiter but I don't know how to make that works and also I tried with NSString methods with no results.

Any help is welcomed, Thank you in advance!!!.

btw sorry about my english XD

2 Answers 2

77

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?

2
  • Yep, the thing is that all the data is going to the same array, i need to have 2 arrays, so in the table I can show the state and as a detail text the country. Thanks for answering. Aug 3, 2011 at 22:38
  • 6
    If the answer helped then you should select it as the correct response. Mar 12, 2014 at 16:34
10

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];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.