-1

Let's say i have a string with this format:

"1,3 litres of water, 2,5 pounds of something ,1,4 pounds of something else"

I would like to obtain an array with elements from the string, elements that are separated by ",".

how could i replace the "," with ".", but only when it is between 2 digits?

So the initial array would look like : "1.3 litres of water, 2.5 pounds of something ,1.4 pounds of something else"

Thanks

4

2 回答 2

4

您可以使用正则表达式来实现:

NSString *string = @"1,3 litres of water, 2,5 pounds of something ,1,4 pounds of something else";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([0-9]+),([0-9]+)" options:0 error:nil];
NSString * newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, string.length) withTemplate:@"$1.$2"];
NSLog(@"%@", newString); // 1.3 litres of water, 2.5 pounds of something ,1.4 pounds of something else

现在,如果您想将其分成一个数组,您可以执行以下操作:

NSArray *array = [newString componentsSeparatedByString:@","];
于 2012-03-19T13:13:53.317 回答
0

一般而言,创建一个执行以下操作的正则表达式:替换(\d+),(\d+)$1\.$2

http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

于 2012-03-19T13:16:24.350 回答