2.7. Chomping a String

Problem

You need to remove a trailing newline or carriage return from a string.

Solution

Use StringUtils.chomp( ) to remove the last line termination sequence from a string:

String input = "Hello\n";
String chomped = StringUtils.chomp( input );
// chomped equals "Hello"

String input2 = "Another test\r\n";
String chomped2 = StringUtils.chomp( input2 );
// chomped2 equals "Another test";

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.