0

I am trying to capitalize each letter in the given string recursively. I have tried this code:

public static String recs(String s){
    return Character.toString(Character.toUpperCase(s.charAt(0)))+recs(s.substring(1));
}

But this code is showing java.lang.StringIndexOutOfBoundsException: String index out of range: 0 exception.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Because at one point the string you pass will be empty, with no char to access. you need an early return check. and why use recursion for this? seems like a waste of everything and just making it complicated and unefficient – JayC667 Mar 20 '21 at 17:29

3 Answers3

0

You need an exit condition for an empty string where you return "", because otherwise it tries getting the first index of the empty array, which results in the error.

Code for this:

if(s.isEmpty()) {
        return s;
    }

return Character.toString(Character.toUpperCase(s.charAt(0)))+recs(s.substring(1));
0

You are not handling the base case when the String is empty, or all the characters have already been capitalized.

public static String recs(String s){
  return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + recs(s.substring(1));
}

Demo

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You need to add a base case when the string is empty:

public static void main(String[] args) {
    System.out.println(recs("hello world"));
}
public static String recs(String s){
    if(s.length() == 0) { return s; }
    return Character.toUpperCase(s.charAt(0)) + recs(s.substring(1));
}

Output:

HELLO WORLD
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48