Andy
Andy

Reputation: 27

Converting a sting to structure in objective-c

I have this string a:10,b:xx,e:20,m:xy,w:30,z:50

But, the keys and the value change...

I want to convert it to a structure in objective-c (I want the app to convert the string to structure automatically, not manually)

In PHP the result will be:

 $array = array(
      'a' => 10, // or 'a' => "10" (doesn't matter)
      'b' => "xx",
      'e' => 20, // or 'e' => "20" (doesn't matter)
      'm' => "xy",
      'w' => 30, // or 'w' => "30" (doesn't matter)
      'z' => 50  // or 'z' => "50" (doesn't matter)
 );

So, how can I convert that string to structure and get the result like in the PHP example but to do it in objective-c... ?

Please show me the exact code, I'm new to objective-c :)

Thank you

Upvotes: 0

Views: 184

Answers (3)

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

That PHP structure looks more like a dictionary to me, so I'm going to assume it is.

NSString *s = @"a:10,b:xx,e:20,m:xy,w:30,z:50";
NSArray *pairs = [s componentsSeparatedByString:@","];
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];

for (NSString *pair in pairs)
{
    NSArray *keyValue = [pair componentsSeparatedByString:@":"];
    [keys addObject:[keyValue objectAtIndex:0]];
    [values addObject:[keyValue objectAtIndex:1]];
}

NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@"%@", dict);

That is obviously pretty verbose, but it requires some fancy string manipulation.

Output looks like:

{
    a = 10;
    b = xx;
    e = 20;
    m = xy;
    w = 30;
    z = 50;
}

Upvotes: 2

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31720

NSString* myString = @"a:10,b:xx,e:20,m:xy,w:30,z:50";

Use below method of NSString.

- (NSArray *)componentsSeparatedByString:(NSString *)separator

NSArray* myArray = [myString componentsSeparatedByString:@","];
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
for (NSString* stringObj in myArray) 
{
     NSArray *myTemp1 = [stringObj componentsSeparatedByString:@":"];
    [myDictionary setObject:[myTemp1 objectAtIndex:0] forKey:[myTemp1 objectAtIndex:1]];
}

Now myDictionary instance is equivalent to $array

Upvotes: 1

cem
cem

Reputation: 3321

You can explode the string, explode the fragments again and put all that into a dictionary. This should work:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *str = @"a:10,b:xx,e:20,m:xy,w:30,z:50";
NSArray *arr = [str componentsSeparatedByString:@","];
for (NSString *fragment in arr) {
    NSArray *keyvalue = [fragment componentsSeparatedByString:@":"];
    [dict setObject:[keyvalue objectAtIndex:0] forKey:[keyvalue objectAtIndex:1]];
}

Upvotes: 1

Related Questions