0

I searched for method to calculate how many times a character is in String and found a good solution

temp.length() - temp.replaceAll("T", "").length()

here,we are calculating the number of time 'T' is in temp...

Problem is,it is not working properly for '.'

Code:

public static void main(String[] args) {
    String temp="TTT..####";
    System.out.println(temp.length() - temp.replaceAll("T", "").length());
    System.out.println(temp.length() - temp.replaceAll(".", "").length());
    System.out.println(temp.length() - temp.replaceAll("#", "").length());
}

OutPut:

run:
3
9
4
BUILD SUCCESSFUL (total time: 1 second)

according to output '.' is 9 times in String.through loop it's gives the right answer. What is the problem??

Sameer Azeem
  • 548
  • 2
  • 9
  • 22

3 Answers3

4

Use replaceAll("\\.", "").length());

replaceAll() takes a REGEX as input. . has a special meaning in REGEX, it means any character. You need to escape it by using 2 \\s

EDIT:

Use :

String temp = "TTT..####";
System.out.println(temp.split("\\.", -1).length - 1);

// using -1 as limit in split() divides the String based on the passed argument (and gives empty Strings as result, if needed). So, in the split array you will have n+1 elements, where n is the number of occurances of the particular argument. So, we are doing length-1.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • before i was using temp.split("#").length-1'#' and '.' were generating error.solved for '.' using your change.but not working for '#'Any suggestion? – Sameer Azeem Aug 06 '14 at 11:35
  • @SameerAzeem - You don't need to escape the `#`. `System.out.println(temp.length() - temp.replaceAll("#", "").length());` will work.. Is it not working? – TheLostMind Aug 06 '14 at 11:37
  • it's working but temp.split("#").length-1 is more short and also for info.plz? – Sameer Azeem Aug 06 '14 at 11:42
1

replaceAll() takes a regex and . mathces any char. This is the reason why your output is 9 in this case

sadhu
  • 1,429
  • 8
  • 14
1

You can find the number of times for every character in one iteration like this

Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < temp.length(); i++)
{
    char c = temp.charAt(i);
    if(!map.containsKey(c))
    {
        map.put(c, 1);
    }
    else
    {
        map.put(c, map.get(c)+1);
    }
}
for(Character c : map.keySet())
{
    System.out.println("" + c + " : " + map.get(c));
}

People have already answered that you need to use \\. instead of . in the regex. I just figured this could be a slightly more general solution for this particular problem with some minor alteration.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428