2016-03-03 71 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;