Java program to count the occurrences of each character
Write a Java program which prints number of occurrences of each characters and also it should not print repeatedly occurrences of duplicate characters as given in the example:
Examples:
Input : geeksforgeeks Output : Number of Occurrence of g is:2 Number of Occurrence of e is:4 Number of Occurrence of k is:2 Number of Occurrence of s is:2 Number of Occurrence of f is:1 Number of Occurrence of o is:1 Number of Occurrence of r is:1
The idea is to create a count array of size 256. Traverse input string and for every character increment its count.
class NoOfOccurenceOfCharacters { static final int MAX_CHAR = 256; static void getOccuringChar(String str) { // Create an array of size 256 i.e. ASCII_SIZE int count[] = new int[MAX_CHAR]; int len = str.length(); // Initialize count array index for (int i = 0; i < len; i++) count[str.charAt(i)]++; // Create an array of given String size char ch[] = new char[str.length()]; for (int i = 0; i < len; i++) { ch[i] = str.charAt(i); int find = 0; for (int j = 0; j <= i; j++) { // If any matches found if (str.charAt(i) == ch[j]) find++; } if (find == 1) System.out.println("Number of Occurrence of " + str.charAt(i) + " is:" + count[str.charAt(i)]); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = "geeksforgeeks"; getOccuringChar(str); } } |
chevron_right
filter_none
Output:
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
Recommended Posts:
- Count occurrences of a given character using Regex in Java
- Java program to count the occurrence of each character in a string using Hashmap
- Count occurrences of elements of list in Java
- Count occurrence of a given character in a string using Stream API in Java
- Java Program to get a character from a String
- Find the count of M character words which have at least one character repeated
- Java Program to convert Character Array to IntStream
- Java Program to Count set bits in an integer
- Java Program to Check if count of divisors is even or odd
- Java Program for Count ways to reach the n'th stair
- Java program to count the characters in each word in a given sentence
- Java Program to Count Inversions in an array | Set 1 (Using Merge Sort)
- Java Program to Count number of binary strings without consecutive 1's
- Java Program to Count trailing zeroes in factorial of a number
- Remove all occurrences of an element from Array in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



