Count the occurrences of a letter in a string

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

提交回复
热议问题