Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...