You can use split to find all the matches
String number = "128";
String digit = "2";
// expensive but simple.
int matches = number.split(digit).length - 1;
Say you want to use a loop and something like contains.
// no objects
char digit="2";
int count = 0;
for (int pos = number.indexOf(digit); pos >= 0; pos = number.indexOf(digit, pos + 1)
count++;
This would be faster, however not so simple.
As @Kon suggests you could iterate over the characters
char digit="2";
for (char ch : number.toCharArray()) // creates an object
if (ch == digit)
count++;
or
// no objects
char digit="2";
for (int i = 0; i < number.length(); i++)
if (number.charAt(i) == digit)
count++;
String has some interesting runtime optimisations and I suspect the second method is fastest, though you would have to test it to check.
4
solved how do you count the number of digits in an int?