Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

2.7. Chomping a String

2.7.1. Problem

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

2.7.2. 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";

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.