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.
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 aMap<Character, Integer>
you will store these characters and their number of occurrences. I suggest you useLinkedHashMap<Character, Integer>
which assures the order of the insertion.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:
After Java 8 (
string.split("")
returns an array of Strings, you need to map them to characters):In both cases the output will be the same:
No need for a regex to solve your problem, if you are using Java8+ you can just use :
outputs
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 :
Outputs