easy for usual numbers, but telephone numbers can start with 01-...., as an example, 01234 is basically 1234 for java, right?
So I can't divide by 10 recursively to find out how many digits there are. is there any different way to find out how many digits there are?
thanks in advance. ps.: no regex if possible
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. 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
"049-4912394129".codePoints().filter( Character::isDigit ).count(); // 13
If you are talking about a number that represented by a String object then:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.