parsing array elements in iPhone

*爱你&永不变心* 提交于 2020-03-05 06:29:04

问题


    NSBundle *bundle = [NSBundle mainBundle];
    NSString *pthpath = [bundle pathForResource:@"path" ofType:@"txt"];
    NSString *content = [NSString stringWithContentsOfFile:pthpath encoding:NSUTF8StringEncoding error:nil];
    array=[[NSArray alloc ]init];
    array = [content componentsSeparatedByString:@"~"];
=====================================================================

here content is:

87,348~51,347~135,132~182,133~268,346~236,347~159,168~87,347@118,298~115,297~200,298~189,266~128,265~117,299@222,352~268,353~264,340~219,342~225,355@186,262~199,299~212,297~195,257~188,260

and array is:

"87,348", "51,347", "135,132", "182,133", "268,346", "236,347", "159,168", "87,347@118,298", "115,297", "200,298", "189,266", "128,265", "117,299@222,352", "268,353", "264,340", "219,342", "225,355@186,262", "199,299", "212,297", "195,257", "188,260"

But I want to again create an array by parsing with @. Please help me out...........


回答1:


for (NSString *string in array) {
    NSArray *subArray = [string componentsSeparatedByString:@"@"];
    for (NSString *substring in subArray)
       etc. etc.

(Next time try to have your question better formatted and articulated please.)




回答2:


Instead of using componentsSeparatedByString:, use componentsSeparatedByCharactersInSet: and create a character set with the separators you want.

Also, you are creating an array there (array = [[NSArray alloc] init]) and when you do array = [content componentsSeparatedByString:@"@"] you are leaking the just allocated array. In general, seems like you should read more about how objects and references work.




回答3:


I think from following code you may get some idea, if I understood your question correctly,

NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:1];
    NSArray *tempArray1 = nil;
    NSArray *tempArray2 = nil;
    NSString *content = @"87,348~51,347~135,132~182,133~268,346~236,347~159,168~87,347@118,298~115,297~200,298~189,266~128,265~117,299@222,352~268,353~264,340~219,342~225,355@186,262~199,299~212,297~195,257~188,260";
    tempArray1 = [content componentsSeparatedByString:@"@"];
    for(NSString *string in tempArray1)
    {
        tempArray2 = [string componentsSeparatedByString:@"~"];
        [resultArray addObjectsFromArray:tempArray2];
    }

    NSLog(@"ResultArray :%@", resultArray);


来源:https://stackoverflow.com/questions/6340225/parsing-array-elements-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!