How to remove newlines from beginning and end of a string?

前端 未结 12 620
旧巷少年郎
旧巷少年郎 2020-11-29 03:22

I have a string that contains some text followed by a blank line. What\'s the best way to keep the part with text, but remove the whitespace newline from the end?

12条回答
  •  离开以前
    2020-11-29 03:41

    If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

    Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

     s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
    

    Complete Example:

    public class RemoveLineBreaks {
        public static void main(String[] args) {
            var s = "\nHello\nWorld\n";
            System.out.println("before: >"+s+"<");
            s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
            System.out.println("after: >"+s+"<");
        }
    }
    

    It outputs:

    before: >
    Hello
    World
    <
    after: >Hello
    World<
    

提交回复
热议问题