Search code examples
javastringchartrim

Remove an unknown number of chars from String java


I have the following assignment: Trim the given character from the beginning and end of the given string. For example, if the given string is "aaahappy birthdayaaaaaaa", and the given character is 'a', returns the string "happy birthday". I managed to remove the start but I can't figure out a way to remove the ending. my code:

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

I cannot use trim or replaceAll, only substring. Please give me ideas how to remove the ending without cutting the same character in the middle


Solution

  • forward and backward iterations should be used just to find out the start and end indices for the final string, then a single "subString" call should return the final string.

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