Program to count occurrence of each character in string
Below program to count each character occurred in string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); //Take a input string System.out.println("Enter a input string"); String str=sc.next(); for(int i=0;i<str.length();i++) { int count=0; char a=str.charAt(i); for(int j=0;j<str.length();j++) { char b=str.charAt(j); if(a==b) { count++; } } System.out.println(a + "...." +count); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Enter a input string webencyclop w....1 e....2 b....1 e....2 n....1 c....2 y....1 c....2 l....1 o....1 p....1 |
We can print duplicates character only using below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); //Take a input string System.out.println("Enter a input string"); String str=sc.next(); for(int i=0;i<str.length();i++) { int count=0; char a=str.charAt(i); for(int j=0;j<str.length();j++) { char b=str.charAt(j); if(a==b) { count++; } } System.out.println(a + "...." +count); } } } |
Output:
1 2 3 4 5 6 |
Enter a input string webencyclop e....2 e....2 c....2 c....2 |