Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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.

like image 688
Manohar Gunturu Avatar asked Nov 30 '22 02:11

Manohar Gunturu


1 Answers

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);
like image 61
Alya'a Gamal Avatar answered Dec 05 '22 13:12

Alya'a Gamal