我遇到的问题是我想按顺序解析字符串,例如,解析“一三二”,将其添加到另一个字符串,并打印“一三二”。我正在使用rangeOfString:
,但是当我解析该字符串时,它返回“一二三”。我知道在我的情况下解析的顺序是if
语句的位置,但是我如何按顺序解析该字符串?这是我的代码:
NSString *string = @"one three two";
NSString *newString;
if ([string rangeOfString:@"one"].location != NSNotFound)
{
newString = [newString stringByAppendingString:@"one"];
}
if ([string rangeOfString:@"two"].location != NSNotFound)
{
newString = [newString stringByAppendingString:@"two"];
}
if ([string rangeOfString:@"three"].location != NSNotFound)
{
newString = [newString stringByAppendingString:@"three"];
}
NSLog(@"%@",newString);
答案 0 :(得分:0)
你做错了,你应该使用componentsSeparatedByString:
并排序:
NSString *stringWithNumbersOrdered(NSString *input)
{
static NSArray *numberStrings = nil;
if (!numberStrings)
{
numberStrings = [NSArray arrayWithObjects:@"zero", @"one", @"two", @"three", @"four", @"five", @"six", @"seven", @"eight", @"nine", /* etc. */ nil];
}
NSArray *components = [input componentsSeparatedByString:@" "];
NSArray *componentsSorted = [components sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int value1 = [numberStrings indexOfObject:obj1];
int value2 = [numberStrings indexOfObject:obj2];
return value1 - value2;
}];
return [componentsSorted componentsJoinedByString:@" "];
}