在Java中计算字符串中出现的字符数
我正试着把这个打印出来有多少个字母“a”。 它一直在给我0…有什么帮助吗在Java中计算字符串中出现的字符数,java,count,output,Java,Count,Output,我正试着把这个打印出来有多少个字母“a”。 它一直在给我0…有什么帮助吗 JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { File myfile = chooser.getSelectedFile(); try { Scanner in = new Scanner(myfile);
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
String word = in.nextLine();
int counter = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}
JFileChooser chooser=newjfilechooser();
if(chooser.showOpenDialog(null)=JFileChooser.APPROVE\u选项){
File myfile=chooser.getSelectedFile();
试一试{
扫描仪输入=新扫描仪(myfile);
String word=in.nextLine();
int计数器=0;
for(int i=0;i
除了读取文件时遇到的任何问题外,还可以尝试使用countMatches。它已经存在于普通语言中了,我们也可以用它来代替
比如说
int count = StringUtils.countMatches(word, "a");
计算字符出现次数的更简单(单行)方法是:
int count = word.replaceAll("[^a]", "").length();
这会将每个不是“a”的字符替换为空白-有效地删除它-留下一个只包含原始字符串的“a”字符的字符串,然后得到该字符串的长度。JFileChooser chooser=new JFileChooser();
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
int counter = 0;
while(in.hasNextLine()){
String word = in.nextLine();
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}
if(chooser.showOpenDialog(null)=JFileChooser.APPROVE\u选项){
File myfile=chooser.getSelectedFile();
试一试{
扫描仪输入=新扫描仪(myfile);
int计数器=0;
while(在.hasNextLine()中){
String word=in.nextLine();
for(int i=0;i
Printword
,您得到了什么?您是否尝试在循环之前打印word
?您只检查了第一行。文件中的第一行有“a”吗?@arshajii我得到1604,但这不对,因为当我做“b”时,我也得到1604。@user2856344 1604是什么?字的价值是多少?美丽;也许不是尽可能节省资源,但写起来肯定很快。如何计算字母a和字母b?申报一个新计数器。在第一个if之后的while for循环中,创建一个新的if来检查b,并增加“b”的计数器。就像你为“a”所做的一样,好的,谢谢,还有如何使它既算作“a”又算作“a”?如果有更简单的方法,我需要单独做一个吗?'a和a'或'a或'a'我希望它同时计算'a'和'a',所以它不区分大小写,因为现在它只计算'a'。