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

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

上级 65d807b0
......@@ -845,23 +845,20 @@ public class StringUtils {
*/
public static String trim(String s, boolean leading, boolean trailing,
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) {
int len = s.length(), i = 0;
while (i < len && s.charAt(i) == space) {
i++;
while (begin < end && s.charAt(begin) == space) {
begin++;
}
s = (i == 0) ? s : s.substring(i);
}
if (trailing) {
int endIndex = s.length() - 1;
int i = endIndex;
while (i >= 0 && s.charAt(i) == space) {
i--;
while (end > begin && s.charAt(end - 1) == space) {
end--;
}
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 {
testURL();
testPad();
testReplaceAll();
testTrim();
}
private void testHex() {
......@@ -226,4 +227,28 @@ public class TestStringUtils extends TestBase {
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 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论