将NSString转换为由特定字符分隔的NSDictionary

我需要将这个“5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21”string转换成字典。 分隔“?”

字典会有点像

{ sometext1 = "5", sometext2 = "8", sometext3 = "519223cef9cee4df999436c5e8f3e96a", sometext4 = "EVAL_TIME", sometext5 = "60", sometext6 = "2013-03-21" } 

谢谢 。

将string分解为更小的string并循环。 这是方式

 NSArray *objects = [inputString componentsSeparatedByString:@"?"]; NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; int i = 1; for (NSString *str in objects) { [dict setObject:str forKey:[NSString stringWithFormat:@"sometext%d", i++]]; } 

尝试

 NSString *string = @"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21"; NSArray *stringComponents = [string componentsSeparatedByString:@"?"]; //This is very risky, your code is at the mercy of the input string NSArray *keys = @[@"cid",@"avid",@"sid",@"TLicense",@"LLicense",@"date"]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; for (int idx = 0; idx<[stringComponents count]; idx++) { NSString *value = stringComponents[idx]; NSString *key = keys[idx]; [dictionary setObject:value forKey:key]; } 

编辑:更优化

 NSString *string = @"5?8?3519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21"; NSArray *stringComponents = [string componentsSeparatedByString:@"?"]; NSArray *keys = @[@"cid",@"avid",@"sid",@"TLicense",@"LLicense",@"date"]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjects:stringComponents forKeys:keys]; 

首先用'?'将string分成几个数组。

然后在字典中添加string。

这样的:

 NSString *str = @"5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21"; NSArray *valueArray = [str componentsSeparatedByString:@"?"]; NSMutableArray *keyArray = [[NSMutableArray alloc] init]; for (int i = 0; i <[valueArray count]; i ++) { [keyArray addObject:[NSString stringWithFormat:@"sometext%d",i+1]]; } NSDictionary *dic = [[NSDictionary alloc] initWithObjects:valueArray forKeys:keyArray]; 

对未来而言:如果要将数据存储为JSON格式(更接近您所拥有的数据),那么在系统之间处理和传输将变得更加容易。 你可以轻松地阅读它…使用NSJSONSerialization