开发者

Best way to split strings into an array

开发者 https://www.devze.com 2023-03-24 13:51 出处:网络
I\'m developing a travel app, I have to read a txt file that contain开发者_运维技巧s all the states and countries, as you can notice this is a pretty huge file to read, anyway, this is an example of t

I'm developing a travel app, I have to read a txt file that contain开发者_运维技巧s 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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号