How do I remove a newline from the end of a String?
Author: Deron Eriksson
Description: This Java example shows how to remove a newline from the end of a String.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The chomp() method of the StringUtils class in Commons LangS can be used to remove the last newline character from a String. A newline is defined as \n, \r, and \r\n. If a String ends in \n\r, only the \r will be removed since this the \r is considered to be one newline.

ChompTest.java

package test;

import java.io.IOException;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

public class ChompTest {

	public static void main(String[] args) throws IOException {

		String str1 = "Chomp 1\n";
		String str2 = "Chomp 2\r";
		String str3 = "Chomp 3\r\n";
		String str4 = "Chomp 4\n\r"; // will remove \r but not \n

		String str1Chomp = StringUtils.chomp(str1);
		String str2Chomp = StringUtils.chomp(str2);
		String str3Chomp = StringUtils.chomp(str3);
		String str4Chomp = StringUtils.chomp(str4);

		System.out.println("Results after chomp (displayed with escaped Java to see special characters)");
		System.out.println("#1:" + StringEscapeUtils.escapeJava(str1Chomp));
		System.out.println("#2:" + StringEscapeUtils.escapeJava(str2Chomp));
		System.out.println("#3:" + StringEscapeUtils.escapeJava(str3Chomp));
		System.out.println("#4:" + StringEscapeUtils.escapeJava(str4Chomp));

	}

}

The console output from ChompTest is shown below. Notice that the \n remains on the last chomped String, since the \r was removed but the \n wasn't.

Results

Results after chomp (displayed with escaped Java to see special characters)
#1:Chomp 1
#2:Chomp 2
#3:Chomp 3
#4:Chomp 4\n