1

我需要将此“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

4 回答 4

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++]];
}
于 2013-04-21T08:56:36.993 回答
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];
于 2013-04-21T09:01:25.013 回答
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];
于 2013-04-26T05:40:02.327 回答
0

面向未来:如果您以 JSON 格式存储数据(无论如何都更接近您所拥有的格式),那么系统之间的处理和传输会容易得多。您可以轻松阅读它...使用 NSJSONSerialization

于 2013-09-26T01:32:15.247 回答