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
  • 779
  • 4
  • 20
  • 44
  • You can get more ideas from this one: [Occurences of substring in a string](http://stackoverflow.com/questions/767759/occurences-of-substring-in-a-string) – Bigger Jul 20 '12 at 06:48

3 Answers3

8

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("\\$");
Bigger
  • 1,807
  • 3
  • 18
  • 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
  • 45,603
  • 8
  • 97
  • 119
2
String s1 = "one$two$three$four!five@six$";

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

int result = s1.length() - s2.length();
Jason Sturges
  • 15,855
  • 14
  • 59
  • 80