@TOC模拟String类中trim()方法
个人写法
今天在学习的过程中,有一道题目的要求就是模拟trim()的方法,来实现字符串两端空格的剔除。
下面是我的写法。
本人没有百度、完全凭借自己的想法写的,在我看来,自己写的还是很复杂的,我认为是我的知识点相对薄弱,能力有限,有待提升。
//模拟trim方法,去除字符串两端的空格
public class TrimTest {
public static void main(String[] args) {
String str = "Ab c d e f ";
String newStr = trimMode(str);
System.out.println(newStr);
System.out.println(str.trim());
}
public static String trimMode(String str) {
char[] chars = str.toCharArray();
char[] chars1 = new char[str.length() - 1];//两端只有一个空格
char[] chars2 = new char[str.length() - 2];//两端都有空格
if (chars[0] != ' ' && chars[chars.length - 1] != ' ') {//没有空格
return str;
} else if (chars[0] == ' ' && chars[chars.length - 1] != ' ') {//第一个字符为空格
for (int i = 1; i < chars.length; i++) {
chars1[i - 1] = chars[i];
}
return new String(chars1);
} else if (chars[0] != ' ' && chars[chars.length - 1] == ' ') {//最后一个字符为空格
for (int i = 0; i < chars.length - 1; i++) {
chars1[i] = chars[i];
}
return new String(chars1);
} else if (chars[0] == ' ' && chars[chars.length - 1] == ' ') {//都有空格
for (int i = 1; i < chars.length - 1; i++) {
chars2[i-1] = chars[i];
}
return new String(chars2);
}
return null;
}
}
在实现功能后。我去看源码,发现源码写的超级简单,真的很佩服!
相比较而言,我的就挺复杂了。
public String trim() {
int len = value.length;
int st = 0;
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[st] <= ' ')) {
st++;
}
while ((st < len) && (val[len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
}
每天进步一点点,加油!