parsing array elements in iPhone

2019-08-22 01:28发布

    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...........

3条回答
beautiful°
2楼-- · 2019-08-22 02:07

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.

查看更多
一纸荒年 Trace。
3楼-- · 2019-08-22 02:19
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.)

查看更多
姐就是有狂的资本
4楼-- · 2019-08-22 02:19

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);
查看更多
登录 后发表回答