2016-03-03 85 views
-2

我給它有一堆話.txt文件數字和符號,這裏是什麼樣子的樣本:閱讀信件和避免

Legs 
m%cks 
animals 
s3nt!m4nts 

我需要創建讀取這個代碼.txt文件,並將沒有數字和符號的單詞放入數組中。所以基本上我必須把雙腿和動物放進一個陣列中。另外兩個字我要打印出來。

public class Readwords { 
    public static void main(String[] args) { 
     String[] array=new string[10]; 
    } 
} 

如何讓程序僅讀取字母而忽略數字和符號?

回答

0

您可以使用正則表達式來查找數字和符號,然後替換它們。

1)。將整個.txt文件讀取到一個字符串中。

2)。使用replaceAll函數替換不需要的字符。

String str = your text; 

str = str.replaceAll(your regex, ""); 
+0

OP並不想改變替換不想要的字符 –

0

你可以試試這個:

try { 
    BufferedReader file = new BufferedReader(new FileReader("yourfile.txt") 
    String line; 
    ArrayList<String> array = new ArrayList<String>(); 

    while ((line = file.nextLine()) != null) { 
     if (line.matches("[a-zA-Z]+")) 
      array.add(line); 
     else 
      System.out.println(line); 
    } 

    String[] result = array.toArray(new String[array.size()]); 

    file.close(); 
    return result; 
} 
catch (Exception e) 
    e.printStackTrace;