Java program to count the occurrences of each character
The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2, ‘o’ -1, ‘g’-2, ‘a’-1,’m’-2, ‘I’-1, ’n’-1. There are different methods for finding the character's cout.
Several ways to determine how frequently each character appears. Examples of them include:
- By using the Counter Array
- By Java HashMap
- By using a Naive Approach
- By using the Java8
1. By usinga Naive Approach
It is one of the simplest methods for finding the occurrence of a character.
Example: CountOOfChar1.java
// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
// A class CountOOfChar1 is created
public class CountOOfChar1
{
static final int MAX_CHAR = 256;
static void getOccuringChars(String st)
{
// an array was created with the size of 256 ( Ascii values)
int counts[] = new int[MAX_CHAR];
// a variable for finding the length of the String given as input
int length = st.length();
// the index value of the count array is initialized
for (int i = 0; i < length; i++)
counts[st.charAt(i)]++;
// an array which has the size as the length of the String is created
char cha[] = new char[st.length()];
for (int i = 0; i < length; i++)
{
cha[i] = st.charAt(i);
int finds = 0;
for (int j = 0; j <= i; j++)
{
// if the condition becomes true as the ame character is found
if (st.charAt(i) == cha[j])
finds++;
}
if (finds == 1)
// display the character count
System.out.println("The count of the "+ st.charAt(i)+ " is: " + counts[st.charAt(i)]);
}
}
// main section of the program
public static void main(String args[])
{
String st = "Preciouspeoplearedangerious"; // a string
//function calling
getOccuringChars(st);
}
}
Output
The count of the character P is: 1
The count of the character r is: 3
The count of the character e is: 5
The count of the character c is: 1
The count of the character i is: 2
The count of the character o is: 3
The count of the character u is: 2
The count of the character s is: 2
The count of the character p is: 2
The count of the character l is: 1
The count of the character a is: 2
The count of the character d is: 1
The count of the character n is: 1
The count of the character g is: 1
2. By using the Counter Array
The counter arrays are utilized in the following Java program to count the instances of each letter in a text. The count variable is increased by 1 at each character-based index by that of the for loop, which iterates across the provided String. If counter[i] is not 0, repeat the process and print the characters and frequency.
Example:CountOfChar1.java
// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class CountOfChar1
{
public static void main(String args[])
{
String st;
int i, length;
int counters[] = new int[256];
Scanner sc = new Scanner(System.in);
System.out.print(" Enter the String : ");
// the input is read from the user
st = sc.nextLine();
// the method for finding the length of the given String
length= st.length();
// loop through all the String, measure how often each character appears, and save the results in a counting array.
for (i = 0; i < length; i++)
{
counters[(int) st.charAt(i)]++;
}
// display the count of the characters
for (i = 0; i < 256; i++)
{
if (counters[i] != 0)
{
// display the count of the characters
System.out.println((char) i + " ------> " + counters[i]);
}
}
}
}
Output
Enter the String: prashantdesghj
a ------> 2
d ------> 1
e ------> 1
g ------> 1
h ------> 2
j ------> 1
n ------> 1
p ------> 1
r ------> 1
s ------> 2
t ------> 1
By use of Java HashMap
Characters are a key in the program, and their occurrence is used as a value. To count the number of times each character appears in the provided String, we utilized Java HashMap inside the next Java application. Since the duplicated key is not stored in the hashmap, we know it only holds key and value pairs.
We first turned the provided String into a character array to iterate through the characters array. In the HashMap, change the count. Afterward, we must determine whether or not a key for every character currently exists in the hash map. If it already exists, raise the count variable; otherwise, add it as a new key to the Map and supply the starting value using the count.
Example: CountOfChar2.java
// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
public class CountOfChar2
{
public static void main(String args[])
{
String st = "Websites";
//With char as the key and frequency as the value in a hashing map.
HashMap <Character, Integer> charCounts = new HashMap<>();
for (int i = st.length() - 1; i >= 0; i--)
{
if(charCounts.containsKey(st.charAt(i)))
{
int counts = charCounts.get(st.charAt(i));
charCounts.put(st.charAt(i), ++counts);
}
else
{
charCounts.put(st.charAt(i),1);
}
}
System.out.println(charCounts);
}
}
Output
{b=1, s=2, t=1, e=2, W=1, I=1}
By using Java 8
We have included Java 8 capabilities in the following Java application. The String whose occurrences of the characters are to be collected has first been started. Following that, we produced a Java Map object. To obtain the character's frequency, we carried out several intermediary processes.
The String.Split () function is first used to divide the supplied text into an array. Afterward when the supplied collection is returned as a stream using the Arrays. stream() function.
The String is changed into lower characters in the next intermediate process. To accomplish this, we utilized using Stream. Map () function, which creates a stream from the components in the streaming after performing the particular function on them.
The list members are concatenated, and a temporary reduction procedure is carried out using the collect() method. A Collector that implements a cascaded "group by" action on input items of type T is returned by the Collectors. grouping() function.
We used the Collectors object's counting() function to count all items. The procedure returns a Collector accepting items of type T. If there are no input items, it returns 0. Otherwise, it counts the number of input items.
Example: CountOfChar3.java
// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.*;
public class CountOfChar3
{
public static void main(String args[])
{
//declaring the string input
String st= "primefactors";
Map<String, Long> results = Arrays.stream(st.split("")).map(String::toLowerCase).collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()));
//displaying the result
System.out.println(results);
}
}
Output
{p=1, r=2, i=1, m=1, e=1, f=1, a=1, c=1, t=1, o=1, s=1}
The concept of the Java program that comes after is similar to the program above, with a few exceptions. We utilized the Java Patterns class inside the following Java application.
The compile() function, which converts the provided mathematical equation into the pattern, has been called first. We then invoked the method matcher() to build a matching technique (match the given input against this pattern).
The items kept inside the Map have finally been counted in the items of the Map. Use the affecting approximately() loop to run across the Map after the count. The situation applies to Java 8 or higher versions.
Example: CountOfChar4.java
// this program is for finding the count of each character
//importing the required packages
import java.io.*;
import java.util.*;
import java.util.Scanner;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.Collectors;
import java.util.*;
import java.util.regex.Pattern;
public class CountOfChar4
{
public static void main(String args[])
{
String st = "Programming";
Pattern.compile(".").matcher(st).results().map(m -> m.group().toLowerCase()).collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting())).forEach((k, v) -> System.out.println(k + " repeated " + v + " times"));
}
}
Output
p repeated 1 time
r repeated 2 times
o repeated 1 times
g repeated 2 times
a repeated 1 times
m repeated 2 times
i repeated 1 times
n repeated 1 times