我有这个字符串a:10,b:xx,e:20,m:xy,w:30,z:50
但是,键和值会改变......
我想将其转换为objective-c中的结构 (我希望应用程序自动将字符串转换为结构,而不是手动)
在PHP中,结果将是:
$array = array(
'a' => 10, // or 'a' => "10" (doesn't matter)
'b' => "xx",
'e' => 20, // or 'e' => "20" (doesn't matter)
'm' => "xy",
'w' => 30, // or 'w' => "30" (doesn't matter)
'z' => 50 // or 'z' => "50" (doesn't matter)
);
那么,如何将该字符串转换为结构并获得结果,如在PHP示例中,但是在objective-c中进行...?
请告诉我确切的代码,我是objective-c的新手:)
谢谢
答案 0 :(得分:2)
PHP结构对我来说看起来更像是一本字典,所以我假设它是。
NSString *s = @"a:10,b:xx,e:20,m:xy,w:30,z:50";
NSArray *pairs = [s componentsSeparatedByString:@","];
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
for (NSString *pair in pairs)
{
NSArray *keyValue = [pair componentsSeparatedByString:@":"];
[keys addObject:[keyValue objectAtIndex:0]];
[values addObject:[keyValue objectAtIndex:1]];
}
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
NSLog(@"%@", dict);
这显然非常冗长,但它需要一些奇特的字符串操作。
输出如下:
{
a = 10;
b = xx;
e = 20;
m = xy;
w = 30;
z = 50;
}
答案 1 :(得分:1)
你可以爆炸字符串,再次爆炸片段并将所有内容放入字典中。这应该有效:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSString *str = @"a:10,b:xx,e:20,m:xy,w:30,z:50";
NSArray *arr = [str componentsSeparatedByString:@","];
for (NSString *fragment in arr) {
NSArray *keyvalue = [fragment componentsSeparatedByString:@":"];
[dict setObject:[keyvalue objectAtIndex:0] forKey:[keyvalue objectAtIndex:1]];
}
答案 2 :(得分:1)
NSString* myString = @"a:10,b:xx,e:20,m:xy,w:30,z:50";
使用以下 NSString 的方法。
- (NSArray *)componentsSeparatedByString:(NSString *)separator
NSArray* myArray = [myString componentsSeparatedByString:@","];
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionary];
for (NSString* stringObj in myArray)
{
NSArray *myTemp1 = [stringObj componentsSeparatedByString:@":"];
[myDictionary setObject:[myTemp1 objectAtIndex:0] forKey:[myTemp1 objectAtIndex:1]];
}
现在 myDictionary 实例相当于 $ array