简体   繁体   English

在Java中检测换行

[英]Detecting line breaks in java

I'm writing a huffman tree and I need to know the frequencies of line breaks and spaces. 我正在写霍夫曼树,我需要知道换行和空格的频率。

Using Scanner or InputStreamReader , is there anyway to store sentences with line breaks and spaces into a single String? 使用ScannerInputStreamReader ,是否可以将带有换行符和空格的句子存储到单个String中?

If I have the code below, 如果我有以下代码,

public class HuffmanTreeApp {
    public static void main(String[] args) throws IOException {
        HuffTree theTree = new HuffTree();
        System.out.print("sentence: ");
        String get;
        get = getString();
    }
    public static String getString() throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        String s = br.readLine();
        return s;
    }
    public static char getChar() throws IOException {
        String s = getString();
        return s.charAt(0);
    }
    public static int getInt() throws IOException {
        String s = getString();
        return Integer.parseInt(s);
    }
}

and if my input is 如果我的输入

"you are               
good";

then I wanna store all the characters including line breaks and spaces into this one string variable get . 然后我想将所有字符(包括换行符和空格)存储到此字符串变量get中 So in this case, there will be one line break and one space. 因此,在这种情况下,将有一个换行符和一个空格。

Is this possible? 这可能吗?

Instead of using readLine (which reads characters until it finds a new line character, and then discard it), use read(char[], offset, len), which will capture new lines as well. 与其使用readLine(先读取字符,直到找到一个新的行字符,然后丢弃它),然后使用read(char [],offset,len),它也会捕获新行。

InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

StringBuilder sb = new StringBuilder();
char [] buf = new char[0xff];

while(br.read(buf, 0, 0xff))
{
    sb.append(new String(buf, "utf-8"));
}

String result = sb.toString();

If you are reading from file, you can use 如果您正在读取文件,则可以使用

Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();

If you are taking input from a console you can use any other delimiter to end the reading. 如果要从console获取输入,则可以使用任何其他delimiter来结束读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM