Write a Java Program to Find All Occurrences of a Character in a String with an example. In this java return all Character Occurrences example, we used the While loop to iterate facStr from start to end. Within that, we used the String charAt (facStr.charAt(i)) function to read characters at each index position.
Next, we compared acStr.charAt(i) character with ch character to check whether they are equal. If True, we print that character along with position (not the index position). If you want the extract index position, please replace i + 1 with i.
import java.util.Scanner;
public class FindAllCharOccurence1 {
private static Scanner sc;
public static void main(String[] args) {
String facStr;
char ch;
int i = 0;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter any String = ");
facStr = sc.nextLine();
System.out.print("\nEnter the Character to Find = ");
ch = sc.next().charAt(0);
while(i < facStr.length())
{
if(facStr.charAt(i) == ch) {
System.out.format("\n %c Found at Position %d ", ch, i + 1);
}
i++;
}
}
}
OUTPUT
Java Program to Find All Occurrences of a Character in a String using For Loop
import java.util.Scanner;
public class FindAllCharOccurence2 {
private static Scanner sc;
public static void main(String[] args) {
String facStr;
char ch;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter any String = ");
facStr = sc.nextLine();
System.out.print("\nEnter the Character to Find = ");
ch = sc.next().charAt(0);
for(int i = 0; i < facStr.length(); i++)
{
if(facStr.charAt(i) == ch) {
System.out.format("\n %c Found at Position %d ", ch, i );
}
}
}
}
RESULT
It is another Java example to return all character occurrences in a given string. Here, we separated the logic using the Java functions.
import java.util.Scanner;
public class FindAllCharOccurence3 {
private static Scanner sc;
public static void main(String[] args) {
String facStr;
char ch;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter any String = ");
facStr = sc.nextLine();
System.out.print("\nEnter the Character to Find = ");
ch = sc.next().charAt(0);
FindAllCharacterOccurences(facStr, ch);
}
public static void FindAllCharacterOccurences(String facStr, char ch) {
for(int i = 0; i < facStr.length(); i++)
{
if(facStr.charAt(i) == ch) {
System.out.format("\n %c Found at Position %d ", ch, i);
}
}
}
}
RESULT