0

The following method returns a trimmed string using iteration. How would you approach this recursively? Link to source

    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();
    }
osdalx
  • 3
  • 3
  • 3
    How would *you* do it, and what trouble are you having? – chrylis -cautiouslyoptimistic- Sep 24 '19 at 04:04
  • My first thought was to reduce the string to its smallest size then remove any space it found in the way. The problem is that if the string has a space in the middle such as " This string " then it would remove that space as well. – osdalx Sep 24 '19 at 14:52

1 Answers1

0

You can do it using recursion with taking two extra variables, one for startIndex and one for endIndex. Either you can take these variables in your trimAll method or can declare globally.

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

}

jnrdn0011
  • 417
  • 2
  • 13