作者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/m.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