有没有任何方法可以采取“一”并返回“1”?

时间:2012-03-25 22:55:31

标签: objective-c numbers

我看过NSNumberFormatter,但这没有用,所以有没有办法解析书面数字并将它们变成实际数字?

2 个答案:

答案 0 :(得分:1)

这样的事情会起作用(无论如何都是积极的整数)。这只是一个起点,您必须检查单词是否正确并且可能忽略大写以使其更加健壮:

 [self parseNumberWords:@"five two three"];


-(NSInteger)parseNumberWords:(NSString *)input {
NSArray *wordArray = [NSArray arrayWithObjects:@"zero",@"one",@"two",@"three",@"four",@"five",@"six",@"seven",@"eight",@"nine", nil];
NSArray *words = [input componentsSeparatedByString:@" "];
NSInteger num = 0;
NSInteger j =0;
for (NSInteger i = [words count]; i>0 ;i--) {
    num = num + [wordArray indexOfObject:[words objectAtIndex:i-1]] * pow(10, j);
    j = j+1;
}
NSLog(@"%ld",num);
return num;

}

答案 1 :(得分:0)

NSNumberFormatter会通过NSNumberFormatterSpellOutStyle为您提供一些方法。 NSNumber所做的基本格式化将完成它。

NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterSpellOutStyle];
NSString * numberWordString = @"three one two";
NSMutableString * digitString = [[NSMutableString alloc] init];
// Break up the input string at spaces and iterate over the result
for(NSString * s in [numberWordString componentsSeparatedByString:@" "]){
    // Let the formatter turn each string into an NSNumber, then get
    // the stringValue from that, which will be a digit.
    [digitString appendString:[[nf numberFromString:s] stringValue]] ;
}        
NSLog(@"%@", digitString);    // prints "312"

显然,你必须投入一些工作来处理不同的输入格式,小写,错误的输入(如果nf无法格式化,这将会崩溃 - 它将返回nil这是appendString:)等的非法论据