java – How it is correct to learn an amount of certain characters in String/Integer'e?


Colleagues, the question is: How can you correctly find out the number of certain characters in String / Integer'e? Let's say there is a string 1110001101011 – I need to find out the number of ones or zeros from it, how can I do this in Java? There are no standard methods…


Probably the easiest way would be to parse the string character by character and compare each element separately, something like:

String str = "1100011";
int countNulls=0, countOnes = 0;
for (char element : str.toCharArray()){
    if (element == '0') countNulls++;
    if (element == '1') countOnes++;
Scroll to Top