Convert NSString to NSDictionary separated by specific character

久未见 提交于 2019-12-24 12:03:05

问题


I need to convert this "5?8?519223cef9cee4df999436c5e8f3e96a?EVAL_TIME?60?2013-03-21" string into dictionary. Separated by "?"

Dictionary would be some thing like

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

Thank you .


回答1:


Break the string to smaller strings and loop for them. This is the way

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



回答2:


Try

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

EDIT: More optimized

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



回答3:


first separate the string into several arrays by '?'.

then add the string in you dictionary.

sth like this:

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



回答4:


For the future: If you were to store your data in JSON format (closer to what you have anyway), it'll be much easier to deal with and transfer between systems. You can easily read it...using NSJSONSerialization



来源:https://stackoverflow.com/questions/16129433/convert-nsstring-to-nsdictionary-separated-by-specific-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!