top of page

Java Program to find occurrence of Character in a String

In this post, we will learn how to find the occurrence of the character in a string using the function.


Implementation Using Java:

public class CharOccurrence {
	static void countEachChar(String str) {
	    int counter[] = new int[256]; 
		int len = str.length(); 
		for (int i = 0; i < len; i++) 
			counter[str.charAt(i)]++; 
		char array[] = new char[str.length()]; 
	        for (int i = 0; i < len; i++) { 
		   array[i] = str.charAt(i); 
		   int flag = 0; 
		   for (int j = 0; j <= i; j++) { 

			if (str.charAt(i) == array[j])  
				flag++;                 
		   } 
                    if (flag == 1)  
		      System.out.println(" The Occurrence of char " + str.charAt(i)
			 + " in the String is:" + counter[str.charAt(i)]);             
		} 
	   } 
	   public static void main(String[] args) 
	   {  
		String str = "This is Programmers Door"; 
		countEachChar(str); 
	   } 
}
Output:
The occurrence of char T in the String is:1
The occurrence of char h in the String is:1
The occurrence of char i in the String is:2
The occurrence of char s in the String is:3
The occurrence of char P in the String is:1
The occurrence of char r in the String is:4
The occurrence of char o in the String is:3
The occurrence of char g in the String is:1
The occurrence of char a in the String is:1
The occurrence of char m in the String is:2
The occurrence of char e in the String is:1
The occurrence of char D in the String is:1
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

7 views0 comments

Recent Posts

See All
bottom of page