How to count occurrence of each character in java string using Pattern Class(Regex)

末鹿安然 提交于 2019-12-04 19:21:22

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

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 .

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}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!