我有以下任务: 从给定字符串的开头和结尾修剪给定字符。 例如,如果给定字符串是“aaahappybirthdayaaaaaaa”,并且给定字符是“a”,则返回字符串“happybirthday”。 我设法删除了开头,但我找不到删除结尾的方法。 我的代码:
public static String trim(String str, char c) {
String newStr = "";
for (int i = 0; i < str.length () && str.charAt (i) == c; i++) {
newStr = str.substring (i+1);
}
String ans = "";
for (int j = 0; j<newStr.length () && newStr.charAt (j) == c; j++) {
ans = newStr.substring (0,j);
}
return ans;
}
我不能使用修剪或replaceAll,只能使用子字符串。 请给我一些想法,如何删除结尾而不在中间剪切相同的字符
最佳答案
应该使用前向和后向迭代来找出最终字符串的开始和结束索引,然后单个“subString”调用应该返回最终字符串。
public static String trim(String str, char c) {
int begIndex = 0;
while (begIndex<str.length() && str.charAt(begIndex) == c) {
begIndex++;
}
int endIndex = str.length()-1;
while (endIndex>= 0 && str.charAt(endIndex) == c) {
endIndex--;
}
return str.substring(begIndex, endIndex+1);
}
关于java - 从 String java 中删除未知数量的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53114033/