请问在这篇文中,找出a的字母出现了多少次(JAVA)?

来源:百度知道 编辑:UC知道 时间:2024/06/06 11:08:42
请问在这篇文中,找出a的字母出现了多少次?
找出war的字母出现了多少次?
WASHINGTON - Rampant government corruption may derail the fight against the Taliban and al-Qaida in Afghanistan even if as many as 80,000 additional U.S. troops are sent to the war, the top military commander there has concluded, according to U.S. officials briefed on his recommendations.

字符串的问题,没有不能用正则表达式解决的

public static void main(String[] args) {
String string = "WASHINGTON - Rampant government corruption may derail the fight against the Taliban and al-Qaida in Afghanistan even if as many as 80,000 additional U.S. troops are sent to the war, the top military commander there has concluded, according to U.S. officials briefed on his recommendations";
Pattern pattern = Pattern.compile("war");
Matcher matcher = pattern.matcher(string);

int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}

用正则表达式.
Pattern p = Pattern.compile("a");
String str = "WASHINGTON - Rampant government corruption m.... ";
Matcher m = p.matcher(str);
int a = 0;
while(m.find()){
a++;
}
System.out.println("a出现了:"+ a );