From fbb0f7f88c84001e0a92dae6a71b7e43bda65a56 Mon Sep 17 00:00:00 2001 From: Benedikt Ritter Date: Fri, 11 Apr 2014 13:28:30 +0000 Subject: [PATCH] LANG-995: Fix bug with stripping spaces on last line in WordUtils.wrap(). This fixes #18 from github. Thanks to Andrey Khobnya git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1586649 13f79535-47bb-0310-9956-ffa450edef68 --- src/changes/changes.xml | 1 + src/main/java/org/apache/commons/lang3/text/WordUtils.java | 6 +++++- .../java/org/apache/commons/lang3/text/WordUtilsTest.java | 6 ++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 4bb337171..24c3ac5e3 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -22,6 +22,7 @@ + Fix bug with stripping spaces on last line in WordUtils.wrap() diff --git a/src/main/java/org/apache/commons/lang3/text/WordUtils.java b/src/main/java/org/apache/commons/lang3/text/WordUtils.java index 6340ca429..ce21d92b2 100644 --- a/src/main/java/org/apache/commons/lang3/text/WordUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/WordUtils.java @@ -183,11 +183,15 @@ public class WordUtils { int offset = 0; final StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32); - while (inputLineLength - offset > wrapLength) { + while (offset < inputLineLength) { if (str.charAt(offset) == ' ') { offset++; continue; } + // only last line without leading spaces is left + if(inputLineLength - offset <= wrapLength) { + break; + } int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset); if (spaceToWrapAt >= offset) { diff --git a/src/test/java/org/apache/commons/lang3/text/WordUtilsTest.java b/src/test/java/org/apache/commons/lang3/text/WordUtilsTest.java index 417751c52..6be8ded79 100644 --- a/src/test/java/org/apache/commons/lang3/text/WordUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/text/WordUtilsTest.java @@ -71,6 +71,12 @@ public class WordUtilsTest { expected = "Click here," + systemNewLine + "http://commons.apache.org," + systemNewLine + "to jump to the" + systemNewLine + "commons website"; assertEquals(expected, WordUtils.wrap(input, 20)); + + // leading spaces on a new line are stripped + // trailing spaces are not stripped + input = "word1 word2 word3"; + expected = "word1 " + systemNewLine + "word2 " + systemNewLine + "word3"; + assertEquals(expected, WordUtils.wrap(input, 7)); } @Test