提交 498f58ec authored 作者: Evgenij Ryazanov's avatar Evgenij Ryazanov

Do not call substring() twice in StringUtils.trim()

上级 65d807b0
...@@ -845,23 +845,20 @@ public class StringUtils { ...@@ -845,23 +845,20 @@ public class StringUtils {
*/ */
public static String trim(String s, boolean leading, boolean trailing, public static String trim(String s, boolean leading, boolean trailing,
String sp) { String sp) {
char space = (sp == null || sp.length() < 1) ? ' ' : sp.charAt(0); char space = sp == null || sp.isEmpty() ? ' ' : sp.charAt(0);
int begin = 0, end = s.length();
if (leading) { if (leading) {
int len = s.length(), i = 0; while (begin < end && s.charAt(begin) == space) {
while (i < len && s.charAt(i) == space) { begin++;
i++;
} }
s = (i == 0) ? s : s.substring(i);
} }
if (trailing) { if (trailing) {
int endIndex = s.length() - 1; while (end > begin && s.charAt(end - 1) == space) {
int i = endIndex; end--;
while (i >= 0 && s.charAt(i) == space) {
i--;
} }
s = i == endIndex ? s : s.substring(0, i + 1);
} }
return s; // substring() returns self if start == 0 && end == length()
return s.substring(begin, end);
} }
/** /**
......
...@@ -39,6 +39,7 @@ public class TestStringUtils extends TestBase { ...@@ -39,6 +39,7 @@ public class TestStringUtils extends TestBase {
testURL(); testURL();
testPad(); testPad();
testReplaceAll(); testReplaceAll();
testTrim();
} }
private void testHex() { private void testHex() {
...@@ -226,4 +227,28 @@ public class TestStringUtils extends TestBase { ...@@ -226,4 +227,28 @@ public class TestStringUtils extends TestBase {
StringUtils.replaceAll("abcabcabc", "aBc", "")); StringUtils.replaceAll("abcabcabc", "aBc", ""));
} }
private void testTrim() {
assertEquals("a a",
StringUtils.trim("a a", true, true, null));
assertEquals(" a a ",
StringUtils.trim(" a a ", false, false, null));
assertEquals(" a a",
StringUtils.trim(" a a ", false, true, null));
assertEquals("a a ",
StringUtils.trim(" a a ", true, false, null));
assertEquals("a a",
StringUtils.trim(" a a ", true, true, null));
assertEquals("a a",
StringUtils.trim(" a a ", true, true, ""));
assertEquals("zzbbzz",
StringUtils.trim("zzbbzz", false, false, "z"));
assertEquals("zzbb",
StringUtils.trim("zzbbzz", false, true, "z"));
assertEquals("bbzz",
StringUtils.trim("zzbbzz", true, false, "z"));
assertEquals("bb",
StringUtils.trim("zzbbzz", true, true, "z"));
}
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论