Best way to split strings into an array
Asked Answered
T

2

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

Tilsit answered 2/8, 2011 at 22:24 Comment(0)
L
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?

Lilybel answered 2/8, 2011 at 22:40 Comment(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.Tilsit
If the answer helped then you should select it as the correct response.Landreth
M
11

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];
Million answered 18/2, 2015 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.