[英]how count the number of digits of telephone numbers?
easy for usual numbers, but telephone numbers can start with 01-...., as an example, 01234 is basically 1234 for java, right?对于普通号码来说很容易,但电话号码可以以 01-.... 开头,例如,对于 java,01234 基本上是 1234,对吧?
So I can't divide by 10 recursively to find out how many digits there are.所以我不能递归地除以 10 来找出有多少位数。 is there any different way to find out how many digits there are?
有什么不同的方法可以找出有多少位数?
thanks in advance.提前致谢。 ps.: no regex if possible
ps.:如果可能,不要使用正则表达式
Assume that the phone number is a string,假设电话号码是一个字符串,
String pn = "049-4912394129" // that's a random value
then you could iterate in that string and check if a character is indeed a number然后你可以迭代那个字符串并检查一个字符是否确实是一个数字
int count = 0;
for(char c : pn.toCharArray()){
if(Character.isDigit(c))
count++;
}
As you phone number is an int, you don't need to bother with regex and every locale phone number patterns.由于您的电话号码是一个整数,因此您无需为正则表达式和每个区域设置电话号码模式而烦恼。
Simply convert your int
phone number to a String.只需将您的
int
电话号码转换为字符串。 Then you can easily get the string length.然后你可以很容易地得到字符串的长度。
int myIntNumber = 1234;
String myStringNumber = String.valueOf(myIntNumber);
int length = myStringNumber.length();
this could easily be done with a lambda这可以通过 lambda 轻松完成
"049-4912394129".codePoints().filter( Character::isDigit ).count(); // 13
If you are talking about a number that represented by a String object then:如果您正在谈论由字符串 object 表示的数字,那么:
public int getNumberOfDigits(phoneNumber) {
int count = 0;
for (int i = 0, i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
count++;
}
}
System.out.println("Number of digits: " + count);
return count;
}
If you are talking about a number that represented by an int then simply convert it to String before using it like so:如果您正在谈论一个由 int 表示的数字,那么只需在使用它之前将其转换为 String,如下所示:
String phoneNumber = String.valueOf(phoneNumberInInt);
I assumed you DO want to count the zeros as a digit because you are not summarizing the value of them, so they do have a meaning when you talk about how many digits are there.我假设您确实想将零视为一个数字,因为您没有总结它们的值,因此当您谈论那里有多少个数字时,它们确实有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.