Count the occurrences of a letter in a string

前端 未结 10 1528
礼貌的吻别
礼貌的吻别 2021-01-21 03:42

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

相关标签:
10条回答
  • 2021-01-21 04:04

    try the indexOf() method. it should work

    0 讨论(0)
  • 2021-01-21 04:05
    1. You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
    2. Define a variable, such as count to count the occurrences of a letter in a given string.
    3. Loop the string and compare each char, if the char is equal to the char to search, then count++;

    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);
    
    0 讨论(0)
  • 2021-01-21 04:08

    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
    
    0 讨论(0)
  • 2021-01-21 04:10

    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
    
    0 讨论(0)
提交回复
热议问题