Count the occurrences of a letter in a string

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

    Try this:

    Char letter = '';
    String sentence = "";
    System.out.println("Enter a character for which to search");
    letter = in.next().charAt(0);
    System.out.println("Enter the string to search");
    sentence = in.next();
    
    int count= 0;
    for (int i = 0; i < sentence.length(); i++) {
        char ch = sentence.charAt(i);
        if (ch==letter) {
            count++;
        }
    }
    System.out.print(letter+" occurance:"+count);
    

提交回复
热议问题