2012-10-16 52 views
0

我是新來的ios,試圖做這樣的事情如何使用NSDictionary中拆分字符串和交換值

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

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

我想交換這是「FULLNAME」的價值,這是我想它是姓氏,名字

我試過各種方法,但它不會工作。有人能告訴我如何做到這一點?

謝謝

回答

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); 
+0

我怎麼把它放回字典? – Hades

+0

要回答這個問題,我需要更多地瞭解字典。通常,確保字典是可變的,然後使用'[dict setObject:revname forKey:@「FULLNAME」]'(在從數組和外部字典中提取它之後)。 – Krumelur

+0

完美,謝謝! – Hades

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

希望這有助於

+0

感謝張貼:)沒有嘗試你的,上述作品。 – Hades