如何将此字符串@“base + unit1 + unit2(unit3 + unit4)”转换为数组

时间:2014-01-27 11:54:47

标签: ios objective-c

如何转换NSString *formula = @"base+unit1+unit2(unit3+unit4)"; 到数组{base,+,unit1,+,unit2,(,unit3,+,unit4,)}

任何人都可以解决这个问题。

2 个答案:

答案 0 :(得分:5)

NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"+()"];
NSArray *elements = [inputString componentsSeparatedByCharactersInSet:charSet];

编辑实际上,由于+()字符不会出现在数组中,因此无法正常工作。哦,好吧。

答案 1 :(得分:1)

NSString *formula = @"base+unit1+unit2(unit3+unit4)";
formula =[formula stringByReplacingOccurrencesOfString:@"+" withString:@",+,"];
formula =[formula stringByReplacingOccurrencesOfString:@"(" withString:@",(,"];
formula =[formula stringByReplacingOccurrencesOfString:@")" withString:@",),"];
if([[formula substringWithRange:NSMakeRange(formula.length-1,1)] isEqualToString:@","])
    formula = [formula substringWithRange:NSMakeRange(0,formula.length-1)];
NSArray *items = [formula componentsSeparatedByString:@","];
NSLog(@"Needed array %@",items);

您还可以使用上述类型的代码来获取请求。