从 String java 中删除未知数量的字符

Remove an unknown number of chars from String java

我有以下作业: Trim 给定字符串开头和结尾的给定字符。 例如,如果给定的字符串是 "aaahappy birthdayaaaaaaa",而给定的字符是 'a',则 returns 的字符串是 "happy birthday"。 我设法删除了开头,但我想不出删除结尾的方法。 我的代码:

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;
}

我不能使用 trim 或 replaceAll,只能使用子字符串。 请给我一些想法如何在不删除中间相同字符的情况下删除结尾

您可以使用以下方法还原您的字符串:

new StringBuilder(yourString).reverse().toString();

然后再把你的方法放在上面。

可以同时在两个方向遍历字符串:

public static String trim(String str, char c) {    
    int start = 0, end = str.length - 1;
    boolean foundStart = false, foundEnd = false;
    for (int i = 0, j = str.length - 1; i < str.length (); i++, j--) {
       if (str.charAt(i) != c && !foundStart) {
         start = i; foundStart = true;
       }

       if (str.charAt(j) != c && !foundEnd) {
         end = j; foundEnd = true;
       }

       if (foundStart && foundEnd) {
          break;
       }
    }

    return str.subString(start, end + 1);
}

编码这是Whosebug编辑器,如果有语法问题请原谅:)

希望对您有所帮助!!

public static String trim(String str, char c) {
    int beginIndex = -1, endIndex = str.length();

    for (int i = 0, j = str.length() - 1; i <= j; i++, j--) {
        beginIndex += beginIndex + 1 == i && str.charAt(i) == c ? 1 : 0;
        endIndex -= i != j && endIndex - 1 == j && str.charAt(j) == c ? 1 : 0;
    }

    return str.substring(beginIndex + 1, endIndex);
}

前向和后向迭代应该只用于找出最终字符串的开始和结束索引,然后单个 "subString" 调用应该 return 最终字符串。

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);
}

你可以做的更简单

public static void main(String[] args) {

    String str = "aaahappy birthdayaaaaaaa";
    char c = 'a';
    String newStr = str.replaceAll("(^["+c+"]+|["+c+"]+$)", "");
    System.out.println(newStr);

}

public static String getTrimmedString(String s, char c) {

    int i = 0;
    int len = s.length();

    while (i<len && s.charAt(i)==c){
        i++;
    }
    while(len>i && s.charAt(len-1)==c){
        len--;
    }
    return s.substring(i, len);
}