how to count special character in a string

android, java

Solution

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("\\$");

Problem

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.

Original source

Related problems