How to count occurrence of each character in java

2020-07-30 01:04发布

问题:

I am trying to find a number of Occurrence of each character on the given string.

  • Expected output: t=2 e=1 s=1 i=1 n=1 g=1
  • Current output:T=0 e=0 s=0 t=0 i=0 n=0 g=0

Code:

String str = "Testing";
int count = 0;

Pattern p = Pattern.compile("[a-zA-Z]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);

while (m.find()) {
    if (m.group().equals(str)) {
        count++;
    }
    System.out.println(m.group() + "=" + count);
}

There are many ways of doing this but I am looking for Regex only, so how can we achieve that by using Regex. Any Help would be Appreciated. Thanks in advance.

回答1:

No need for a regex to solve your problem, if you are using Java8+ you can just use :

String input = "Testing";
Map<String, Long> result = Arrays.stream(input.split(""))
        .map(String::toLowerCase)
        .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));

outputs

{t=2, e=1, s=1, i=1, n=1, g=1}

Edit

mmm, Pattern in this case is useless I don't advice to use it in this problem, as an alternative solution using Pattern with results from Java9+ you can use :

String str = "Testing";
Pattern.compile(".").matcher(str)
        .results()
        .map(m -> m.group().toLowerCase())
        .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))
        .forEach((k, v) -> System.out.println(k + " = " + v)); 

Outputs

t = 2
e = 1
s = 1
i = 1
n = 1
g = 1


回答2:

There are a lot of ways of achieving the result, but Regex is not a tool for this one. If you want to filter the characters and assure only [a-zA-Z] will be count, filter the unwanted characters with: string = string.replaceAll("[^a-zA-Z]", "");. Now back to your issue.

You need to split String to characters and a Map<Character, Integer> you will store these characters and their number of occurrences. I suggest you use LinkedHashMap<Character, Integer> which assures the order of the insertion.

char[] charArray = string.toCharArray();
Map<Character, Integer> map = new LinkedHashMap<>();

Now loop through the characters and save them to the map. If a character has already been stored, increment the value by one. This might be achieved with a procedural and traditional for-loop or since Java 8 you can use java-stream.

Before Java 8:

for (char ch: charArray) {
    if(map.containsKey(ch)){
        map.put(ch, map.get(ch)+1);
    } else {
        map.put(ch, 1);
    }
}

After Java 8 (string.split("") returns an array of Strings, you need to map them to characters):

Map<Character, Long> map = Arrays
    .asList(string.split("")).stream().map(s -> s.charAt(0))
    .collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));

In both cases the output will be the same:

System.out.println(map); // prints {t=2, e=1, s=1, i=1, n=1, g=1}