删除多行开头的整数

xan*_*xan 1 java string integer

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

22Ahmedabad, AES Institute of Computer Studies
526Ahmedabad, Indian Institute of Managment
561Ahmedabad, Indus Institute of Technology & Engineering
745Ahmedabad, Lalbhai Dalpatbhai College of Engineering
Run Code Online (Sandbox Code Playgroud)

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

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){}
}
Run Code Online (Sandbox Code Playgroud)

但它输出一个空白文件.

mel*_*okb 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();
Run Code Online (Sandbox Code Playgroud)