我的实现思路:
使用到双指针,从字符串的两边(开始和结尾)往中间走,直到找到不为空格的索引位置就停下来。然后将剩余的部分进行遍历。
代码演示:
public class TrimSimulate {
public static void main(String[] args) {
String s = trimSimulate(" sdfsdfss sdf ");
System.out.println(s);
}
public static String trimSimulate(String str) {
String targetStr = "";
int i = 0,j = str.length() - 1;
int start = 0;
int end = 0;
while (i < j){
String currentValuei = String.valueOf(str.charAt(i));
String currentValuej = String.valueOf(str.charAt(j));
if (currentValuei.contains(" ")){
i++;
}else if (currentValuej.contains(" ")){
j--;
}else {
start = i;
end = j;
break;
}
}
for (int k = start; k <= end; k++) {
targetStr += str.charAt(k);
}
return targetStr;
}
}
结果:
优化:
//去掉首尾空格,优化
public static String trimSimulate1(String str) {
String targetStr = "";
int start = 0 , end = str.length() -1;
while (start < end){
if (str.charAt(start) == ' '){
start++;
}else if (str.charAt(end) == ' '){
end--;
}else {
break;
}
}
for (int i = start; i <= end; i++) {
targetStr += str.charAt(i);
}
// 或者使用String的内部方法截取
// String substring = str.substring(start, end+1);
return targetStr;
}
不足之处请指正~