ios - 将其分解为可用字符串的最佳方法是什么

标签 ios arrays nsstring

解析这个问题的最佳方法是什么?

字符串: 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/

相关文章:

ios - header 在 UITableView Controller 中不可见

c - 为什么 puts() 函数会给我一个心形符号?

ios - NSDateFormatter用于“2014年1月1日”

ios - WKWebView 在点击广告时没有响应。控制台消息 : [Accessibility] WKContentView

ios - 应用程序将终止通知

ios - swift : AppDelegate and NSManagedObjectContext are nil

java - 如何将 Vector 更改为 ArrayList?

java - 为什么我的 View 数组返回 null?

ios - 如何从十六进制字符串获取 NSData?

iphone - 从 NSString 中提取子字符串的线程