开发者

Find count of digits in string variable

I have a string wh开发者_高级运维ich 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.


A cleaner solution using Regular Expressions:

// matches all non-digits, replaces it with "" and returns the length.
s.replaceAll("\\D", "").length()


String s = "2485083572085748";
int count = 0;
for (int i = 0, len = s.length(); i < len; i++) {
    if (Character.isDigit(s.charAt(i))) {
        count++;
    }
}


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

"2485083572085748".chars()
                  .filter(Character::isDigit)
                  .count();


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!


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);


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;
}


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.


int count = 0;
for(char c: str.toCharArray()) {
    if(Character.isDigit(c)) {
        count++;
    }
}

Also see

  • Javadoc


Something like:

using System.Text.RegularExpressions;


            Regex r = new Regex( "[0-9]" );
            Console.WriteLine( "Matches " + r.Matches("if string contains 2485083572085748 then" ).Count );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜