To count number of 1's,0's,2's in a string in java

java, string

Solution

If you only need to search for `1's,0's,2's` so yo can try something like this :

 String content = "0011221100";
 int zeros = content.length() - content.replaceAll("0", "").length();
 int ones = content.length() - content.replaceAll("1", "").length();
 int twos = content.length() - content.replaceAll("2", "").length();
 System.out.println("0's:" + zeros);
 System.out.println("1's:" + ones);
 System.out.println("3's:" + twos);

Problem

I'm new to the java string operations. Let consider a string contains 0's,1's,2's like show below ``` String content = "0011221100"; ``` You may ask me a question that why don't you store it in integer,Because in my case I should have to use the string only. The output be: ``` 0's:4 1's:4 2's:2 ``` How can I achieve it.

Original source