Reputation: 287
I have a string which sometimes gives character value and sometimes gives integer value. I want to get the count of number of digits in that string.
For example, if string contains "2485083572085748" then total number of digits is 16.
Please help me with this.
Upvotes: 6
Views: 81337
Reputation: 328
in JavaScript:
str = "2485083572085748"; //using the string in the question
let nondigits = /\D/g; //regex for all non-digits
let digitCount = str.replaceAll(nondigits, "").length;
//counts the digits after removing all non-digits
console.log(digitCount); //see in console
Thanks --> https://stackoverflow.com/users/1396264/vedant for the Java version above. It helped me too.
Upvotes: 1
Reputation: 101
Just to refresh this thread with stream option of counting digits in a string:
"2485083572085748".chars()
.filter(Character::isDigit)
.count();
Upvotes: 9
Reputation: 1679
public static int getCount(String number) {
int flag = 0;
for (int i = 0; i < number.length(); i++) {
if (Character.isDigit(number.charAt(i))) {
flag++;
}
}
return flag;
}
Upvotes: 2
Reputation: 240860
int count = 0;
for(char c: str.toCharArray()) {
if(Character.isDigit(c)) {
count++;
}
}
Also see
Upvotes: 0
Reputation: 18819
A cleaner solution using Regular Expressions:
// matches all non-digits, replaces it with "" and returns the length.
s.replaceAll("\\D", "").length()
Upvotes: 28
Reputation: 1632
If your string gets to big and full of other stuff than digits you should try to do it with regular expressions. Code below would do that to you:
String str = "asdasd 01829898 dasds ds8898";
Pattern p = Pattern.compile("\d"); // "\d" is for digits in regex
Matcher m = p.matcher(str);
int count = 0;
while(m.find()){
count++;
}
check out java regex lessons for more. cheers!
Upvotes: 3
Reputation: 1
Something like:
using System.Text.RegularExpressions;
Regex r = new Regex( "[0-9]" );
Console.WriteLine( "Matches " + r.Matches("if string contains 2485083572085748 then" ).Count );
Upvotes: -3
Reputation: 63688
Loop each character and count it.
String s = "2485083572085748";
int counter = 0;
for(char c : s.toCharArray()) {
if( c >= '0' && c<= '9') {
++counter;
}
}
System.out.println(counter);
Upvotes: 2
Reputation: 50087
String s = "2485083572085748";
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
count++;
}
}
Upvotes: 18