Skip to content

Commit ad5072a

Browse files
Shenker93jhoeller
authored andcommitted
optimize StringUtils trimLeadingWhitespace() / trimTrailingWhitespace() & trimLeadingCharacter() / trimTrailingCharacter() utility methods
1 parent 687c398 commit ad5072a

File tree

1 file changed

+16
-16
lines changed

1 file changed

+16
-16
lines changed

spring-core/src/main/java/org/springframework/util/StringUtils.java

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -271,11 +271,11 @@ public static String trimLeadingWhitespace(String str) {
271271
return str;
272272
}
273273

274-
StringBuilder sb = new StringBuilder(str);
275-
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
276-
sb.deleteCharAt(0);
274+
int beginIdx = 0;
275+
while (beginIdx < str.length() && Character.isWhitespace(str.charAt(beginIdx))) {
276+
beginIdx++;
277277
}
278-
return sb.toString();
278+
return str.substring(beginIdx);
279279
}
280280

281281
/**
@@ -289,11 +289,11 @@ public static String trimTrailingWhitespace(String str) {
289289
return str;
290290
}
291291

292-
StringBuilder sb = new StringBuilder(str);
293-
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
294-
sb.deleteCharAt(sb.length() - 1);
292+
int endIdx = str.length() - 1;
293+
while (endIdx >= 0 && Character.isWhitespace(str.charAt(endIdx))) {
294+
endIdx--;
295295
}
296-
return sb.toString();
296+
return str.substring(0, endIdx + 1);
297297
}
298298

299299
/**
@@ -307,11 +307,11 @@ public static String trimLeadingCharacter(String str, char leadingCharacter) {
307307
return str;
308308
}
309309

310-
StringBuilder sb = new StringBuilder(str);
311-
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
312-
sb.deleteCharAt(0);
310+
int beginIdx = 0;
311+
while (beginIdx < str.length() && leadingCharacter == str.charAt(beginIdx)) {
312+
beginIdx++;
313313
}
314-
return sb.toString();
314+
return str.substring(beginIdx);
315315
}
316316

317317
/**
@@ -325,11 +325,11 @@ public static String trimTrailingCharacter(String str, char trailingCharacter) {
325325
return str;
326326
}
327327

328-
StringBuilder sb = new StringBuilder(str);
329-
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
330-
sb.deleteCharAt(sb.length() - 1);
328+
int endIdx = str.length() - 1;
329+
while (endIdx >= 0 && trailingCharacter == str.charAt(endIdx)) {
330+
endIdx--;
331331
}
332-
return sb.toString();
332+
return str.substring(0, endIdx + 1);
333333
}
334334

335335
/**

0 commit comments

Comments
 (0)