从字符串中删除换行符不起作用

时间:2017-03-26 22:55:52

标签: java

我正在尝试从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.

这就是我需要的......

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 个答案:

答案 0 :(得分: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;
      }
    }
  }
}