如何使用nsdictionary分割字符串和交换值

时间:2012-10-16 10:49:35

标签: objective-c ios

我是ios的新手,试图做这样的事情

self.dataArray = [dictionary valueForKey:@"LIST"];

{
  "List": [
    {
      "FULLNAME": "FirstName, LastName",
      "ID": "281"
    }
  ]
}

我想交换'FULLNAME'中的值,即我希望它是LastName,FirstName

我尝试了各种方法,但它不起作用。有人能告诉我如何做到这一点吗?

谢谢

2 个答案:

答案 0 :(得分:3)

假设您知道如何进行字典操作,这里是交换字符串中元素的一种方法:

NSString* name = @"Firstname, Lastname";
// Remove the space after comma (not necessary if you know the name will always
// have a space after comma, then just split on ', '.
NSString* normalizedName = [name stringByReplacingOccurrencesOfString:@", " withString:@","];
// Split the string on ','.
NSArray* nameParts = [normalizedName componentsSeparatedByString:@","];
// Reverse the array
NSArray* reverseNameParts = [[nameParts reverseObjectEnumerator] allObjects];
// Join the array with ', '
NSString* revname = [reverseNameParts componentsJoinedByString:@", "];
NSLog(@"Reversed name parts: %@", revname);

答案 1 :(得分:1)

我相信它应该是objectForKey而不是valueForKey,如果你的字典包含数组。

self.dataArray = [dictionary objectForKey:@"LIST"];
    for(NSString *fullname in self.dataArray){
        if([fullname isEqualToString:@"FULLNAME"]){
            NSArray *name = [fullname componentsSeparatedByString:@","];
            NSMutableString* reverseName = [NSMutableString string];
            for (int i=[name count]-1; i>=0;i--){
                [reverseName appendFormat:@", ", [name objectAtIndex:i]];
                //reverse name should be what you are looking for..or something close
            }
        }
    }

希望这会有所帮助