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

时间:2013-04-21 08:49:16

标签: iphone ios objective-c nsstring nsdictionary

我需要将此“5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21”字符串转换为字典。用“?”分隔

字典就像是

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

谢谢。

4 个答案:

答案 0 :(得分:5)

将字符串分解为较小的字符串并为它们循环。 这是方式

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++]];
}

答案 1 :(得分:4)

尝试

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];

答案 2 :(得分:0)

首先用'?'将字符串分成几个数组。

然后在字典中添加字符串。

像这样:

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];

答案 3 :(得分:0)

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

轻松阅读它