Count the occurrences of a letter in a string

前端 未结 10 1531
礼貌的吻别
礼貌的吻别 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: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
    

提交回复
热议问题