英文:
how count the number of digits of telephone numbers?
问题
容易处理常规数字,但电话号码可以以01-....开头,例如,01234在Java中基本上就是1234,对吗?
因此,我无法通过递归地除以10来找出有多少位数字。有没有其他方法可以找出有多少位数字?
提前感谢。
附:如果可能的话,请不要使用正则表达式。
英文:
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
答案1
得分: 2
假设电话号码是一个字符串,
String pn = "049-4912394129"; // 这是一个随机值
然后你可以在该字符串中进行迭代,检查字符是否确实是一个数字
int count = 0;
for(char c : pn.toCharArray()){
if(Character.isDigit(c))
count++;
}
英文:
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++;
}
答案2
得分: 0
因为您的电话号码是一个整数,所以无需使用正则表达式和各种地区的电话号码模式。
只需将您的int
类型电话号码转换为字符串。然后您可以轻松地获取字符串的长度。
int myIntNumber = 1234;
String myStringNumber = String.valueOf(myIntNumber);
int length = myStringNumber.length();
英文:
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();
答案3
得分: 0
这可以很容易地使用 Lambda 表达式来完成:
"049-4912394129".codePoints().filter(Character::isDigit).count(); // 13
英文:
this could easily be done with a lambda
"049-4912394129".codePoints().filter( Character::isDigit ).count(); // 13
答案4
得分: 0
如果您正在谈论由String对象表示的数字,则:
public int getNumberOfDigits(String phoneNumber) {
int count = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
count++;
}
}
System.out.println("数字的位数:" + count);
return count;
}
如果您正在谈论由int表示的数字,那么在使用之前只需将其转换为String,如下所示:
String phoneNumber = String.valueOf(phoneNumberInInt);
我假设您确实希望将零视为一位数字,因为您没有总结其值,所以在谈论有多少位数字时它们是有意义的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论