1

我有一个txt文件有超过一千行文本,在开始时有一些整数。像:

22Ahmedabad, AES Institute of Computer Studies
526Ahmedabad, Indian Institute of Managment
561Ahmedabad, Indus Institute of Technology & Engineering
745Ahmedabad, Lalbhai Dalpatbhai College of Engineering

我想将所有行存储在另一个没有整数的文件中。我写的代码是:

while (s.hasNextLine()){
    String sentence=s.nextLine();
    int l=sentence.length();
    c++;
    try{//printing P
        FileOutputStream ffs = new FileOutputStream ("ps.txt",true);
        PrintStream p = new PrintStream ( ffs );
        for (int i=0;i<l;i++){
            if ((int)sentence.charAt(i)<=48 && (int)sentence.charAt(i)>=57){
                p.print(sentence.charAt(i));
            }
        }
        p.close();
    }   
    catch(Exception e){}
}

但它输出一个空白文件。

4

3 回答 3

5

您的代码中有几处需要改进:

  1. 不要用每一行重新打开输出文件。一直开着就好了。
  2. 您正在删除所有数字,而不仅仅是开头的数字 - 这是您的意图吗?
  3. 你知道任何一个既是<= 48又是同时>= 57的数字吗?
  4. Scanner.nextLine()不包括换行,所以你需要p.println()在每一行之后调用。

试试这个:

// open the file once
FileOutputStream ffs = new FileOutputStream ("ps.txt");
PrintStream p = new PrintStream ( ffs );

while (s.hasNextLine()){
    String sentence=s.nextLine();
    int l=sentence.length();
    c++;
    try{//printing P
        for (int i=0;i<l;i++){
            // check "< 48 || > 57", which is non-numeric range
            if ((int)sentence.charAt(i)<48 || (int)sentence.charAt(i)>57){
                p.print(sentence.charAt(i));
            }
        }

        // move to next line in output file
        p.println();
    }   
    catch(Exception e){}
}

p.close();
于 2013-01-21T23:07:57.303 回答
2

您可以将此正则表达式应用于从文件中读取的每一行:

String str = ... // read the next line from the file
str = str.replaceAll("^[0-9]+", "");

正则表达式^[0-9]+匹配行首的任意数量的数字。replaceAll方法用空字符串替换匹配项。

于 2013-01-21T23:09:39.250 回答
0

在 mellamokb 评论之上,您应该避免使用“幻数”。无法保证这些数字会落在 ASCII 代码的预期范围内。

您可以使用简单地检测字符是否为数字Character.isDigit

String value = "22Ahmedabad, AES Institute of Computer Studies";

int index = 0;
while (Character.isDigit(value.charAt(index))) {
    index++;
}
if (index < value.length()) {
    System.out.println(value.substring(index));
} else {
    System.out.println("Nothing but numbers here");
}

(Nb dasblinkenlight 发布了一些出色的正则表达式,它可能更容易使用,但如果你喜欢,正则表达式会彻底颠覆我的大脑:P)

于 2013-01-21T23:13:22.053 回答