我正在嘗試從文本文件中讀取單詞並將其存儲在數組中。我試過的代碼中的問題如下所示,它讀取所有字符,如「words」和「讀。」但我只想在數組中使用「單詞」和「閱讀」。從字符串中移除除az之外的所有字符
public String[] openFile() throws IOException
{
int noOfWords=0;
Scanner sc2 = new Scanner(new File(path));
while(sc2.hasNext())
{
noOfWords++;
sc2.next();
}
Scanner sc3 = new Scanner(new File(path));
String bagOfWords[] = new String[noOfWords];
for(int i = 0;i<noOfWords;i++)
{
bagOfWords[i] =sc3.next();
}
sc3.close();
sc2.close();
return bagOfWords;
}
括號和+是沒有必要的,你只需要[^ A-ZA-Z]。如果您解釋了正則表達式模式以及replaceAll如何使用它,它可能會有利於OP。 – Shar1er80
是的,我知道,我認爲+會代替一組字符而不是每個字符。所以它不會浪費每個正則表達式匹配的內存地址 –