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

12

176

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?

Copy answered 17/9, 2011 at 11:17 Comment(2)
Possible duplicate of Removing whitespace from strings in JavaLattonia
No it's not. The question in the link is asking about 'replace' rather..Shattuck
S
368

Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.

String trimmedString = myString.trim();
Sheldonshelduck answered 17/9, 2011 at 11:19 Comment(1)
The question is about newlines. This removes more than just newlinesAgglutinin
B
32
String.replaceAll("[\n\r]", "");
Baggs answered 17/9, 2011 at 11:51 Comment(1)
Bro, @JohnB It will remove all the new line character in between the string as well. the ask is to remove only the leading & trailing new line character.Bulger
P
26

This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:

String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:

String.replaceAll("^[\n\r]", "")
Pinelli answered 24/2, 2020 at 15:36 Comment(3)
Could you provide extra context to your answer? That way everyone can understand what your code does and why.Hose
I have added explanations to my answer. I hope that now it is clear.Pinelli
This is the correct solution because it only removes newlines and not spaces, tabs, or other whitespace characters.Oodles
B
12

tl;dr

String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…

The old String::trim method has a strange definition of whitespace.

As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.

Example code.

String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.

You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\t', U+0009 HORIZONTAL TABULATION.
  • It is '\n', U+000A LINE FEED.
  • It is '\u000B', U+000B VERTICAL TABULATION.
  • It is '\f', U+000C FORM FEED.
  • It is '\r', U+000D CARRIAGE RETURN.
  • It is '\u001C', U+001C FILE SEPARATOR.
  • It is '\u001D', U+001D GROUP SEPARATOR.
  • It is '\u001E', U+001E RECORD SEPARATOR.
  • It is '\u001F', U+0
Bioastronautics answered 20/5, 2019 at 21:33 Comment(0)
S
6

If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().

Seduce answered 25/10, 2017 at 23:13 Comment(0)
I
4

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 world\nHello everyone\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
Interplay answered 31/7, 2020 at 12:25 Comment(0)
M
2

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.

Mckinley answered 6/3, 2017 at 7:14 Comment(2)
Yeah but what if you don't know how many lines are at the beginning/end? Your solution assumes there are exactly 2 newlines in both casesFunnyman
The second parameter of split() is just the limit. Leave it off if you want to match an unlimited number of times.Mckinley
K
2

Try this

function replaceNewLine(str) { 
  return str.replace(/[\n\r]/g, "");
}
Kaleidoscope answered 31/7, 2020 at 15:17 Comment(0)
C
1
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
  1. Start of a string = ^ ,
  2. End of a string = $ ,
  3. regex combination = | ,
  4. Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
Cibis answered 18/7, 2018 at 6:26 Comment(0)
H
0

Another elegant solution.

String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
Hypoplasia answered 8/10, 2020 at 3:27 Comment(0)
Z
0

For anyone else looking for answer to the question when dealing with different linebreaks:

string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

This passes these tests:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
Zarathustra answered 28/10, 2020 at 20:58 Comment(0)
P
-5
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");
Peplos answered 20/7, 2014 at 6:44 Comment(2)
This does not correctly answer the question. It removes all CR and LFs, not just those at the beginning and end.Appetizer
This will replace all, not only from the start and the end.Tsarism

© 2022 - 2024 — McMap. All rights reserved.