Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find count of digits in string variable

Tags:

java

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.

like image 824
sUrAj Avatar asked Apr 06 '11 09:04

sUrAj


4 Answers

A cleaner solution using Regular Expressions:

// matches all non-digits, replaces it with "" and returns the length.
s.replaceAll("\\D", "").length()
like image 83
Vedant Agarwala Avatar answered Nov 15 '22 09:11

Vedant Agarwala


String s = "2485083572085748";
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
    if (Character.isDigit(s.charAt(i))) {
        count++;
    }
}
like image 23
Thomas Mueller Avatar answered Nov 15 '22 09:11

Thomas Mueller


Just to refresh this thread with stream option of counting digits in a string:

"2485083572085748".chars()
                  .filter(Character::isDigit)
                  .count();
like image 41
miro Avatar answered Nov 15 '22 07:11

miro


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!

like image 25
Lucas de Oliveira Avatar answered Nov 15 '22 08:11

Lucas de Oliveira