简体   繁体   中英

how do you count the number of digits in an int?

I have been working hard to try and figure out a way to count the number of 2's or whatever digit you want to figure out a way to count the number of 2's and print the amount of 2's in the int.

if i put in a random number like 3552342343 am i am looking for 3's i would want it to print 4 because their is 4 3's.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM