Ashish Ramtri
Ashish Ramtri

Reputation: 81

Counting the number of digits in an integer string in Java

I have a char array (let's say of size 4). I am converting it into a string using:

String str = String.valueOf(cf); // where cf is the char array of size 4.

This String can contain 01 or 11 or 001 or 011, etc. Now, I need to calculate the number of digits in this string. But every single time I calculate the number of digits(preferably in Java), it shows 4 as the result(Maybe due to the size 4). How do I calculate the no. of digits according to input string?

Example: If 001 is the input, it should give o/p as 3 and so on.

Here's the coding part :

static long solve(int k, long n)
    {

  //  System.out.println("Entered Solve function");
  char[] c = new char[4];

  long sum = 0;
  char[] cf = {};

  for(long i=2;i<=n;i++)
  {

      cf = fromDeci(c, k, i);
      String str = String.valueOf(cf);


       //System.out.println(snew);
       sum = sum + str.length() ;
    }

  return sum;
}

Upvotes: 3

Views: 3564

Answers (4)

cactuschibre
cactuschibre

Reputation: 2365

Otherwise, you can use the Apache Commons : (see StringUtils)

For example : StringUtils.getDigits("abc56ju20").size()

It gives you 4.

Upvotes: 0

azro
azro

Reputation: 54148

You can use Stream API from java 8, solution in ONE-LINE :

String s = "101";
int nb = Math.toIntExact(s.chars()                     // convert to IntStream
                          .mapToObj(i -> (char)i)      // convert to char
                          .filter(ch -> isDigit(ch))   // keep the ones which are digits
                          .count());                   // count how any they are

Upvotes: 3

phatfingers
phatfingers

Reputation: 10250

You can verify whether a character is a digit by simple comparison against digit characters.

private int countDigits(char[] cf) {
    int digitCt = 0; 
    for (char c : cf) {
        if ((c >= '0') && (c <= '9')) digitCt++;
    }
    return digitCt;
}

Upvotes: 1

Manuel Manhart
Manuel Manhart

Reputation: 5455

Is very easy with a regex:

String test = "a23sf1";
int count = 0;
Pattern pattern = Pattern.compile("[0-9]");
Matcher  matcher = pattern.matcher(test);
while (matcher.find()) {
    count++;
}
System.out.println(count);

Upvotes: 1

Related Questions