如何从Java中复制粘贴的文本中删除换行符(\ n)?

时间:2019-06-07 13:58:26

标签: java string

我有一个代码来替换用户引入的字符串的某些字符(空格,制表符),然后显示文本:

    System.out.println("Text:");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    try {
        String text = bufferedReader.readLine();
        text = text.replaceAll("\n", "");
        text = text.replaceAll(" ", "");
        text = text.replaceAll("\t", "");
        System.out.println(text);
    } catch (IOException e) {
    }

但是当我粘贴杂色线条的文本时:

First Substring Introduced
Second Substring Introduced
Third Substring Introduced

它仅显示第一个换行符之前的子字符串,例如:

firstSubtringIntroduced

我想获得整个粘贴文本的下一个结果:

FirstSubstringIntroducedSecondSubstringIntroducedThirdSubstringIntroduced

4 个答案:

答案 0 :(得分:2)

在删除每行的制表符和空格之后,尝试将所有行汇总在一起:

StringBuilder sb = new StringBuilder();
String text = "";
try {
    while ((text = br.readLine()) != null) {
        text = text.replaceAll("[\t ]", "");
        sb.append(text);
    }
}
catch (IOException e) {
}

System.out.println(sb);

这里的问题是您的BufferedReader一次只能读取一行。

作为一种替代方案,并且更接近您当前的解决方案,您可以使用System.out.print代替System.out.println,它不会自动打印换行符:

try {
    while ((text = br.readLine()) != null) {
        text = text.replaceAll("[\t ]", "");
        System.out.print(text);
    }
}
catch (IOException e) {
}

答案 1 :(得分:2)

您正在阅读仅一行,即第一行:

SwiftUI

这就是为什么您得到只显示处理的第一行的输出的原因。您应该进行循环,以读取您输入的所有行:

String text = bufferedReader.readLine();  //just one line

第一个循环将打印 FirstSubtringIntroduced ,第二个 SecondSubstringIntroduced ,依此类推,直到处理完所有行。

答案 2 :(得分:1)

请注意,String#replaceAll需要一个正则表达式。 String#replace用第二个参数(这就是您想要的)替换第一个参数的所有出现次数

System.out.println(text.replace("\n", "").replace("\r", ""));

方法名称有点混乱。

答案 3 :(得分:0)

{{1}}

我确实认为这是您所需要的。