统计字符串中指定字符出现的次数,运用Java中index()方法

步骤:(1)创建字符对象文字“字符串对象创建后不能对该字符串的字符做修改”
(2)利用循环查找“字符”文字,每次找到则利用一个变量来记录出现次数,然后重新调整搜索字符串的区域【通过indexOf(int ch,int fromIndex)查找“字符”文字】。
(3)显示字符串中“字符”出现的次数

第1个回答  2016-05-19
package com.zuidaima.util.string;
import java.io.*;
public class CountString {

public static int count(String filename, String target)
throws FileNotFoundException, IOException {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
StringBuilder strb = new StringBuilder();
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
strb.append(line);
}
String result = strb.toString();
int count = 0;
int index = 0;
while (true) {
index = result.indexOf(target, index + 1);
if (index > 0) {
count++;
} else {
break;
}
}
br.close();
return count;
}

public static void main(String[] args) {
try {
System.out.println(count("D:\\zuidaima.txt", "a"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}追问

能不能解释一下呢?看不太懂

本回答被网友采纳
相似回答