java - 如果没有 Java 的 trim() 方法,你将如何递归地修剪字符串?
问题描述
以下方法使用迭代返回修剪后的字符串。你将如何递归地处理这个问题?链接到源
public static String allTrim(String str) {
int j = 0;
int count = 0; // Number of extra spaces
int lspaces = 0;// Number of left spaces
char ch[] = str.toCharArray();
int len = str.length();
StringBuffer bchar = new StringBuffer();
if (ch[0] == ' ') {
while (ch[j] == ' ') {
lspaces++;
j++;
}
}
for (int i = lspaces; i < len; i++) {
if (ch[i] != ' ') {
if (count > 1 || count == 1) {
bchar.append(' ');
count = 0;
}
bchar.append(ch[i]);
} else if (ch[i] == ' ') {
count++;
}
}
return bchar.toString();
}
解决方案
您可以使用递归来获取两个额外的变量,一个用于 startIndex,一个用于 endIndex。您可以在 trimAll 方法中使用这些变量,也可以全局声明。
public class TrimSpace {
static String trimAll(String str, int startIndex, int endIndex){
if(str.charAt(startIndex)!=' ' && str.charAt(endIndex)!=' '){
return str.substring(startIndex, endIndex+1);
}
else if(str.charAt(startIndex)==' ' && str.charAt(endIndex)==' '){
return trimAll(str, startIndex+1, endIndex-1);
}
else if(str.charAt(startIndex)==' ' && str.charAt(endIndex)!=' '){
return trimAll(str, startIndex+1, endIndex);
}
else{
return trimAll(str, startIndex, endIndex-1);
}
}
public static void main(String[] args) {
String str = " hello ";
String result = trimAll(str, 0, str.length()-1);
System.out.println(result);
//to count extra spaces you just need to get the length difference
int extraSpaces = str.length() - result.length();
System.out.println(extraSpaces);
}
}
推荐阅读
- php - 通过UUID使用php更新firebase中的记录
- api - 如何在特定语音通道中获取一组用户?
- c - 如何在 OpenMP 并行区域内声明和 malloc 指针?(错误:段违规(“核心”生成))
- python - 如何在python中使用翻译
- docker - 在 CI/CD 中如何管理前端和后端之间的依赖关系?
- android - 如何在网格布局中调整列的大小?
- proxy - Nexus 3:原始代理存储库对于包含 % 的 url 失败
- wix - 如何更改将安装所有 dll 和其他文件的 wxs 文件中的目录?
- java - TCP数据每20ms发送一次
- ios - HomeKit - 当我从后台返回到前台时,如何更新附件 isReachable 值?