簡體   English   中英

從字符串中刪除除數組中az之外的所有字符

[英]removing all character from string except a-z in array

我正在嘗試從文本文件中讀取單詞,並將其存儲在array中。我嘗試如下所示的代碼存在的問題是它讀取了所有字符,例如“單詞”和“已讀”。 但我只想要數組中的“單詞”和“讀取”。

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;
}

使用正則表達式替換:

replaceAll("([^a-zA-Z]+)","");

並將該行應用於

bagOfWords[i] = sc3.next().replaceAll("([^a-zA-Z]+)","");

使用此代碼:

for (int i = 0; i < noOfWords; i++) {
     bagOfWords[i] = sc3.next().replaceAll("[^A-Za-z0-9 ]", "");
}

您可能只需要字母。 在這種情況下,可以使用Character.isLetter(char)方法。

片段:

String token = "word1";
String newToken = "";
for (int i = 0; i < token.length(); i++) {
    char c = token.charAt(i);
    if(java.lang.Character.isLetter(c)){
        newToken += c;
    }
}
System.out.println(newToken);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM