iosobjective-cnsstringnsarray

How separate my NSString to two different array i.e key and value in Objective-C?


Hello Guys I have one string For example

"Name=Mihir&,Age=34&,Allergy=&,Symptoms=Fever,Sore throat&,Tested=No&,State=Rhode Island"

So I need to convert this string into 2 arrays key and values like one array before = and another array after equal to.
I have done some code but I don't know what to do next!
Please see my code below:

strCustomFields = _incident.CustomFields;
NSLog(@"strCustomFields = %@",strCustomFields);
NSArray *items = [strCustomFields componentsSeparatedByString:@"&,"];  

Here I have separated into array So now I have 6 arrays but now how to make my array to key and value like below?
array1 = Name,Age,Allergy,Symptoms,Tested,State
array2 = Mihir,34,,Fever Sore throat,No,Rhode Island


Solution

  • Got my answer may be it's long way to get that but it works for me.

    NSArray *items = [strCustomFields componentsSeparatedByString:@"&,"];
    NSArray *subArr = nil;
    NSMutableArray *arr1 = [[NSMutableArray alloc] init];
    for (NSString* currentString in items) {
        subArr = [currentString componentsSeparatedByString:@"="];
        [arr1 addObject:[subArr objectAtIndex:0]];
        [arr1 addObject:[subArr objectAtIndex:1]];
        NSLog(@"subArr = %@", subArr);
    }
    NSLog(@"arr1 = %@", arr1);  
    for (int i = 0; i< [arr1 count]/ 2; i++) {  
                myCustomView.lbltitle.text = [NSString stringWithFormat:@"%@", [arr1 objectAtIndex:(i *2)]];
                myCustomView.lblvalue.text = [NSString stringWithFormat:@"%@", [arr1 objectAtIndex:(i * 2) + 1]];
            }