问题描述
我有一个电话号码,格式为易于阅读的电话号码,即 (123) 123-4567
I have a phone number formatted as an easy to read phone number, i.e., (123) 123-4567
但是,当我想在代码中使用该电话号码时,我需要将该字符串解析为一个数字变量(例如 int
)
However, when I want to use that phone number in code, I need to parse that string into a number variable (such as an int
)
但是,[string intValue];
不起作用 - 我在以前的项目中使用了大约一百万次 intValue
,全部没问题,但是在这里,我传入的每个字符串,我都会得到相同的随机 int
退出:
However, [string intValue];
doesn't work - I've used intValue
about a million times in previous projects, all with no problem, however here, every string I pass in, I get the same, random int
back out:
- (int)processPhoneNumber:(NSString *)phoneNumber {
NSMutableString *strippedString = [NSMutableString stringWithCapacity:10];
for (int i=0; i<[phoneNumber length]; i++) {
if (isdigit([phoneNumber characterAtIndex:i])) {
[strippedString appendFormat:@"%c",[phoneNumber characterAtIndex:i]];
}
}
NSLog(@"clean string-- %@", strippedString);
int phoneNumberInt = [strippedString intValue];
NSLog(@"**** %d
&i", phoneNumberInt, phoneNumberInt);
return phoneNumberInt;
}
那么当我调用这个方法时:
Then when I call this method:
NSLog(@"%i", [self processPhoneNumber:self.phoneNumberTextField.text]);
我得到:2147483647
.我给这个方法的每个输入都会返回:2147483647
I get: 2147483647
. Every input I give this method returns: 2147483647
推荐答案
正如 CRD 已经解释的那样,您正在尝试将该字符串转换为太小而无法容纳该值的类型,并且您正在取回最大值该类型的可能值.
As CRD has already explained, you're trying to convert that string to a type that's too small to hold the value, and you're getting back the maximum possible value for that type.
然而,你真正的问题是更深层次的.电话号码"并不是真正的号码.它不代表数量.你永远不会对一个进行算术运算.它实际上是一串数字,你应该这样处理它.不要转换它;只对字符串进行操作.
Your real problem is deeper, however. A phone "number" isn't really a number. It doesn't represent a quantity. You would never perform arithmetic on one. It's actually a string of digits, and you should handle it that way. Don't convert it; just operate on the string.
另请参阅表示电话号码的正确方法是什么?
这篇关于NSString intValue 不能用于检索电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!