解析这个问题的最佳方法是什么?
字符串:
UMversion=2.9&UMstatus=Approved&UMauthCode=152058&UMrefNum=59567592&UMavsResult=Address%3A%20Match%20%26%205%20Digit%20Zip%3A%20Match&UMavsResultCode=YYY&UMcvv2Result=Match&UMcvv2ResultCode=M& UMresult=A&UMvpasResultCode=&UMerror=已批准&UMerrorcode=00000&UMcustnum=&UMbatch= 1&UMbatchRefNum=91016&UMisDuplicate=N&UMconvertedAmount=&UMconvertedAmountCurrency=840&UMconversionRate=&UMcustReceiptResult=No%20Receipt%20Sent&UMprocRefNum=&UMcardLevelResult=A&UMauthAmount=10&UMfiller=filled
我从 Web 服务中将其作为一个大长字符串返回。列出每个变量,然后它们有 a = sign
然后我需要用什么来填充变量。
我需要将所有这些数据放入变量中以进行检查。
那么,我应该如何分解它。
最佳答案
使用这种代码:
NSArray* components = [veryLongString componentsSeparatedByString:@"&"]; // array of strings like "x=y"
NSMutableDictionary* parsedResult = [NSMutableDictionary new];
for (NSString* keyValuePair in components) {
NSArray* keyAndValue = [keyValuePair componentsSeparatedByString:@"="];
NSString* key = keyAndValue[0];
NSString* value = (keyAndValue.count>1) ? keyAndValue[1] : nil;
// remove percent escapes in case we have URL-encoded characters in the value like '%20' and the like
parsedResult[key] = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ?: [NSNull null];
}
NSLog(@"dictionary of parameters: %@", parsedResult);
您最终会得到一个字典,其中包含从您的字符串中提取的键和值。
关于ios - 将其分解为可用字符串的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22619774/