How to remove the carriage return from string while pasting content to Excel file

后端 未结 5 1748
逝去的感伤
逝去的感伤 2020-12-11 03:17

I have a problem while pasting my contents (or text) generated by Java code into excel. The problem is that my Java code generates a String with multiple lines, i.e. with li

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 03:51

    Do you want the carriage return / newline, or don't you? Your title says that you don't, your code is explicitly adding carriage returns when the string has a newline. If you want to get rid of both, use String.replaceAll(), which takes a regex:

    public static void main(String[] argv)
    throws Exception
    {
        String s1 = "this\r\nis a test";
        String s2 = s1.replaceAll("[\n\r]", "");
        System.out.println(s2);
    } 
    

    This example finds any occurrence of the characters, and deletes them. You probably want to look for the sequence of characters and replace with a space, but I'll leave that up to you: look at the doc for java.util.regex.Pattern.

    And I suspect that the "box" is some other character, not a return or newline.

提交回复
热议问题