题解 | #统计字符串中字母出现次数#
统计字符串中字母出现次数
https://www.nowcoder.com/practice/83350872bdb5406fa706895d5efb1c55
我们可以使用在String 类里面的两个函数,确定输入的字母首次出现的位置和最后出现的位置,如果这两个位置一样的话我们可以直接输出一次的,这两个函数分别为:indexOf(String str ,int index )和 lastIndexOf(String str),我们在这个区间之内,每一次寻找,都将返回的非 -1 的位置进行向后移动一位,直到返回值为 -1 结束循环。
import java.util.Scanner; public class Main { public static void main(String[] args) { String string = "H e l l o ! n o w c o d e r"; Scanner scanner= new Scanner(System.in); String word = scanner.next(); scanner.close(); System.out.println(check(string, word)); } public static int check(String str, String word) { //write your code here...... int start = str.indexOf(word) ; int end = str.lastIndexOf(word) ; int index = start ; int count = 0 ; while(true){ if(str.indexOf(word,start) != -1){ count++ ; start = str.indexOf(word,start) + 1; }else{ break ; } } return count ; } }