题解 | #统计字符串中字母出现次数# JAVA30
统计字符串中字母出现次数
http://www.nowcoder.com/practice/83350872bdb5406fa706895d5efb1c55
import java.util.ArrayList;
import java.util.Collections;
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......
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
list.add(str.charAt(i));
}
return Collections.frequency(list, word.charAt(0));
}
public static int check2(String str, String word) {
//write your code here......
int cnt = 0;
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i) == word.charAt(0)) {
cnt++;
}
}
return cnt;
}
public static int check1(String str, String word) {
//write your code here......
int cnt = 0;
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
String s = new String(ch+"");
if(s.equals(word)) {
cnt++;
}
}
return cnt;
}
}