2017-03-26 11 views
-2

Java文字列からキャリッジリターンを削除しようとしていますが、これまでのところ大したことはありません。私は現在、コードワイズを持っています。あなたは私が得ているものと比較して、必要な文字列を見てみることができます。文字列から改行を削除します。

public static void main(String[] args) { 
    String tempString = ""; 
    String tempStringTwo = ""; 
    String [] convertedLines = new String [100]; 
    int counter = 0; 
    int tempcount = 0; 

    File file = new File("input.txt"); 
    if (!file.exists()) { 
     System.out.println(args[0] + " does not exist."); 
    return; 
    } 
    if (!(file.isFile() && file.canRead())) { 
     System.out.println(file.getName() + " cannot be read from."); 
    return; 
    } 
    try { 
     FileInputStream fis = new FileInputStream(file); 
     char current; 

     while (fis.available() > 0) { // Filesystem still available to read bytes from file 
      current = (char) fis.read(); 
      tempString = tempString + current; 
      int character = (int) current; 
      if (character==13) { // found a line break in the file, need to ignore it. 
       //tempString = tempString.replace("\n"," ").replace("\r"," "); 
       tempString = tempString.replaceAll("\\r|\\n", " "); 
       //tempString = tempString.substring(0,tempString.length()-1); 
       //System.out.println(tempString); 
      } 
      if (character==46) { // found a period 
       //System.out.println("Found a period."); 
       convertedLines[counter] = tempString; 
       tempString = ""; 
       counter++; 
       tempcount = counter; 
      } 

     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    System.out.println("------------------------------------------------"); 
    for (int z=0;z<tempcount;z++){ 
     System.out.println(convertedLines[z]); 
    }  
} 

ここ...ここ

The quick brown fox 
jumps over the lazy dogs. 
Now is the time for all good men to come to the 
aid of their country. 
All your base are 
belong to us. 

は、私は必要なものだ...私の現在の出力だ1文字ずつ処理

The quick brown fox jumps over the lazy dogs. 
Now is the time for all good men to come to the aid of their country. 
All your base are belong to us. 
+0

注:EOFを検出するために 'fis.available()> 0'をチェックしないでください。 'fis.read()'のint値をチェックし、 '<0 'ならば中断します。 –

+0

また、 '文字'に割り当てるために 'current'をキャストする必要はありません。あなたは単に 'current'を直接使うことができるので、' character'の必要はありません。 '13'と' 46'を使う必要はなく、代わりに '\ r''と' '.''を使います。 –

+1

なぜ「13」をチェックするの?なぜ、「見つかった期間」ブロック内の 'convertedLines [counter] = tempString.replaceAll(" \\ r | \\ n "、" "); –

答えて

0

はおそらく、この問題に対処する最も簡単な方法です。

import java.io.IOException; 

public class SentencePerLiner { 
    public static void main(String [] args) throws IOException { 
    for (;;) { 
     int ch = System.in.read(); 
     switch (ch) { 
     case '.': 
     System.out.println('.'); 
     break; 
     case '\n': 
     case '\r': 
     break; 
     default: 
     if (ch < 0) return; 
     System.out.print((char) ch); 
     break; 
     } 
    } 
    } 
} 
関連する問題