I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This
Hope this will helpful to you.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the string to search");
String sentence = in.nextLine();
System.out.println("Enter a character for which to search");
String letter = in.next();
int noOfOccurance = 0;
for (int i = 0; i < sentence.length(); i++) {
char dh=letter.charAt(0);
char ch = sentence.charAt(i);
if (dh==ch) {
noOfOccurance++;
}
}
System.out.print(noOfOccurance);
}
}
Sample Input Output:
Enter the string to search
how are you
Enter a character for which to search
o
No of Occurances : 2