
Java Program To Find Occurrence of a Character in a String
In this Java Program, we find the occurrence of the character in a string.
Logic : 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("Occurrence of char" + str.charAt(i)+"in the String is:"+counter[str.charAt(i)]);
}
Step 1 : Create a class Occurrence
Step 2 : Create a method countEachChar()
Step 3 : Create an array counter and store the ASCII values which ranges upto 256 in it.
Step 4 : Create a variable len and store the length of the string in it.
Step 5 : Apply for loop. Initialize i to 0, i should be smaller than length and increment i.
Step 6 : Increment the counter with the string at charAt position i.
Step 7 : Create another array with the size of the string and store the new length of the string in it.
Step 8 : Apply for loop. Initialize i to 0, i should be smaller than length and increment i.
Step 9 : Inside the for loop of i store the string at char i into array[i].
Step 10 : Initialize flag to 0.
Step 11 : Apply for loop of j. Initialize j to 0, i should be smaller and equal to i and increment j.
Step 12 : If a char is found in String then set the flag so that we can print the occurrence of the character.
Step 13 : Create main method, specify the string of which you want to find the occurrence of the character.
Program :
public class Occurrence
{
static void countEachChar(String str)
{
//ASCII values ranges upto 256
int counter [] = new int[256];
//String length
int len = str.length();
//This array holds the occurrence of each char
//For example, ASCII value of A is 65 so if A is found twice then
//counter [65] would have the value 2, here 65 is the ASCII value of A
for(int i = 0; i < len; i++)
counter[str.charAt(i)]++;
//We are creating another array with the size of String
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 a char is found in String then set the flag so that
//we can print the occurrence
if(str.charAt(i) == array[j])
flag++;
}
if (flag == 1)
System.out.println("Occurrence of char" + str.charAt(i)+"in the String is:"+counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = "itengineer8995";
countEachChar(str);
}
}
Output :
Occurrence of chariin the String is:2
Occurrence of chartin the String is:1
Occurrence of charein the String is:3
Occurrence of charnin the String is:2
Occurrence of chargin the String is:1
Occurrence of charrin the String is:1
Occurrence of char8in the String is:1
Occurrence of char9in the String is:2
Occurrence of char5in the String is:1
For execution of the same do visit my YouTube Channel :