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;
}
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
Very simple with 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);
You can check if a character is a digit by simple comparison to digit characters.
private int countDigits(char[] cf) {
int digitCt = 0;
for (char c : cf) {
if ((c >= '0') && (c <= '9')) digitCt++;
}
return digitCt;
}
Otherwise, you can use Apache Commons: (see StringUtils )
For example:
StringUtils.getDigits("abc56ju20").size()
This gives you 4.