Counting the number of digits in an integer string in Java
I have a char array (say size 4). I am converting it to string using:
String str = String.valueOf(cf); // where cf is the char array of size 4.
This string can contain 01
either 11
or 001
or 011
etc. Now I need to calculate the number of digits in this line. But every time I calculate the number of digits (preferably in Java) the result is 4 (possibly because of the size of 4). How to calculate the value of no. digits according to the input line?
Example: if 001 is an input it should give o / p as 3, etc.
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;
}
source to share
Otherwise, you can use Apache Commons: (see StringUtils )
For example:
StringUtils.getDigits("abc56ju20").size()
This gives you 4.
source to share