NickG
NickG

Reputation: 11

Extracting vowels from string using recursion?

Not Sure if this code will work? or if there is another way to write it in a simpler way?

public static String extractVowels(String s, StringBuilder x, int i){
    if(i < s.length()){
      if(s.charAt(i)== 'a' || s.charAt(i)== 'e' || s.charAt(i)== 'i' || 
         s.charAt(i)== 'i' || s.charAt(i)== 'o' || s.charAt(i)== 'u'){
        x = new StringBuilder(s);
        return extractVowels(s,x.deleteCharAt(i), i+1);
      }
    }
    return null;
  }

Upvotes: 0

Views: 2710

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727057

Assuming that you are doing this as a learning exercise to practice recursion, here is what you need to consider:

  • Make your method return the result, rather than appending it to StringBuilder
  • Removing vowels from an empty string produces an empty string
  • Removing vowels from a string that starts in a vowel is the same as removing vowels from a substring that removes the first character
  • Removing vowels from a string that does not start in a vowel is the first character followed by the result of removing vowels from the remaining substring.

English description is a lot longer than Java code:

public static String extractVowels(String s) {
    if (s.length() == 0) {
        return s;
    }
    char c = s.charAt(0);
    if (c == 'a' || c == 'e' || ...) {
        return extractVowels(s.substring(1));
    } else {
        return c+extractVowels(s.substring(1));
    }
}

Upvotes: 2

Related Questions