作者SST2000 (BMW 428i)
看板java
标题请JAVA高手给予指教,文件内搜寻字串的问题
时间Mon Jan 20 13:43:44 2020
请各位JAVA高手给予指教下面是我想出来的在文件内
找寻想要的字串并且统计次数~~~请问有人有更好更方便的方法
可以给予指点吗???
package IOTESTDemo;
import java.io.IOException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.Arrays;
import java.text.ParseException;
public class IODEMOTEST {
public static void main(String[] args) throws IOException
{
ArrayList<Integer> arrayList = new ArrayList<Integer>();
FileReader fr = new FileReader("fr.txt");
int counter=0;
System.out.println("请输入你要找寻的字串");
Scanner scanner = new Scanner(System.in);
String ST=scanner.nextLine();
char[] charArray = {'a', 'b', 'c', 'd', 'e'};
String str2 = new String(charArray);//把字元阵列转成字串
int[] chs = new int[30];
int ch;
int count=0;
while ((ch = fr.read()) != -1)
{
if ((ch != 32))
{
arrayList.add(ch);
if(ch==13)
{
arrayList.remove(arrayList.indexOf(13));
counter=counter+showString(arrayList,ST);
System.out.println("counter=="+counter);
}
if(ch==10)
{
arrayList.remove(arrayList.indexOf(10));
counter=counter+showString(arrayList,ST);
System.out.println("counter=="+counter);
}
} else
{
counter=counter+showString(arrayList,ST);
System.out.println("一共有"+counter+"字串相符合");
//
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++");
}
}
fr.close();
}
//---------------------------------------------------------------------//
public static String ArrayToString(String[] arr) {
//直接呼叫function
return Arrays.toString(arr);
}
public static char byteAsciiToChar(int ascii) {
char ch = (char) ascii;
return ch;
}
public static int showString(ArrayList<Integer> arrayList, String ST)
{
System.out.println("_________________________________________________");
System.out.println("arraysize is="+arrayList.size());
char[] CH = new char[arrayList.size()];
for (int loop = 0; loop < arrayList.size(); loop++) {
CH[loop] = byteAsciiToChar(arrayList.get(loop));
}
for (int loop = 0; loop < arrayList.size(); loop++) {
System.out.print(CH[loop]);
}
System.out.println();
String str3 = new String(CH);
System.out.println(str3.length());
System.out.println("arrayList里面是 "+str3);
String str4 =ST;
arrayList.clear();
if(str4.equals(str3))
{
System.out.println("======="+str4.equals(str3));
return 1;
}
return 0;
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 111.246.156.168 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/java/M.1579499026.A.67A.html
1F:→ ssccg: java其实没必要用这麽多char操作,用字串就好 01/20 17:59
2F:→ ssccg: 整个档读成字串再split("\\s")再算次数 01/20 18:11
3F:→ benqm300: 正规表示式 + Matches = 答案 01/25 08:41