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

前端 未结 12 634
旧巷少年郎
旧巷少年郎 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:51

    I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.

    To remove newlines from the beginning:

    // Trim left
    String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);
    
    System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");
    

    and end of a string:

    // Trim right
    String z = "\n\nfrom the end\n\n";
    
    System.out.println("-" + z.split("\\n+$", 2)[0] + "-");
    

    I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.

    Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.

提交回复
热议问题