From bf39492c34b20435a354864e535a53af2730c5fb Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 4 Jul 2022 18:22:06 +0200 Subject: [PATCH] Introduce StringUtils.trimAllWhitespace(CharSequence) Closes gh-28757 --- .../org/springframework/util/StringUtils.java | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/StringUtils.java b/spring-core/src/main/java/org/springframework/util/StringUtils.java index ef6e215a38..b4573a336b 100644 --- a/spring-core/src/main/java/org/springframework/util/StringUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java @@ -241,21 +241,23 @@ public abstract class StringUtils { } /** - * Trim all whitespace from the given {@code String}: + * Trim all whitespace from the given {@code CharSequence}: * leading, trailing, and in between characters. - * @param str the {@code String} to check - * @return the trimmed {@code String} + * @param text the {@code CharSequence} to check + * @return the trimmed {@code CharSequence} + * @since 5.3.22 + * @see #trimAllWhitespace(String) * @see java.lang.Character#isWhitespace */ - public static String trimAllWhitespace(String str) { - if (!hasLength(str)) { - return str; + public static CharSequence trimAllWhitespace(CharSequence text) { + if (!hasLength(text)) { + return text; } - int len = str.length(); - StringBuilder sb = new StringBuilder(str.length()); + int len = text.length(); + StringBuilder sb = new StringBuilder(text.length()); for (int i = 0; i < len; i++) { - char c = str.charAt(i); + char c = text.charAt(i); if (!Character.isWhitespace(c)) { sb.append(c); } @@ -263,6 +265,21 @@ public abstract class StringUtils { return sb.toString(); } + /** + * Trim all whitespace from the given {@code String}: + * leading, trailing, and in between characters. + * @param str the {@code String} to check + * @return the trimmed {@code String} + * @see #trimAllWhitespace(CharSequence) + * @see java.lang.Character#isWhitespace + */ + public static String trimAllWhitespace(String str) { + if (str == null) { + return null; + } + return trimAllWhitespace((CharSequence) str).toString(); + } + /** * Trim leading whitespace from the given {@code String}. * @param str the {@code String} to check