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
try the indexOf() method. it should work
Example--->
int count = 0;
char charToSearch = letter.toCharArray()[0];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == charToSearch) {
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);
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
No need to loop:
String sentence = "abcabcabcd";
String letter = "b";
int numOfOccurences = sentence.length() -
sentence.replaceAll(letter, "").length();
System.out.println("numOfOccurences = "+numOfOccurences);
OUTPUT:
numOfOccurences = 3