3

Possible Duplicate:
String Functions how to count delimiter in string line

I have a string as str = "one$two$three$four!five@six$" now how to count Total number of "$" in that string using java code.

Community
  • 1
  • 1
sivanesan1
  • 729
  • 4
  • 19
  • 41

3 Answers3

7

Using replaceAll:

    String str = "one$two$three$four!five@six$";

    int count = str.length() - str.replaceAll("\\$","").length();

    System.out.println("Done:"+ count);

Prints:

Done:4

Using replace instead of replaceAll would be less resource intensive. I just showed it to you with replaceAll because it can search for regex patterns, and that's what I use it for the most.

Note: using replaceAll I need to escape $, but with replace there is no such need:

str.replace("$");
str.replaceAll("\\$");
マルちゃん だよ
  • 1,737
  • 3
  • 17
  • 28
3

You can just iterate over the Characters in the string:

    String str = "one$two$three$four!five@six$";
    int counter = 0;
    for (Character c: str.toCharArray()) {
        if (c.equals('$')) {
            counter++;
        }
    }
Keppil
  • 44,655
  • 7
  • 93
  • 116
2
String s1 = "one$two$three$four!five@six$";

String s2 = s1.replace("$", "");

int result = s1.length() - s2.length();
Jason Sturges
  • 15,787
  • 14
  • 60
  • 77