I am practicing recursive methods, and one of the three I am working on attempts to capitalize an entire string and add a space between each character. Below is my code:
public static String toUpper(String str) {
char ch;
if(str.length() == 0) {
return "";
}
ch = str.charAt(0);
if(Character.isLowerCase(ch)){
return Character.toUpperCase(ch) + toUpper(str.substring(1));
}
String newString = ch + toUpper(str.substring(1));
/*
* This is where my issue is.
* I assumed using the replace method would work just as it does on any other string;
* however I am getting incorrect output every time.
*/
return newString.replace("", " ");
}
However, it is replacing with more than just a single space, except for between the first two characters, and I cannot figure out why for the life of me. I have tested this use of replace in another non-recursive method, and it works just as I expect it. If you can help me understand this it would be greatly appreciated.
My output looks like this:
H I T H E R E !
And I want this:
H I T H E R E !
You should not be replacing characters, instead first test that you have at least one character (otherwise return the empty string); if you have at least one character, capitalize the first character and then concatenate it with the result of recursively calling your method. Like,
public static String toUpper(String str) {
if (str.length() < 1) {
return "";
}
return Character.toUpperCase(str.charAt(0)) + toUpper(str.substring(1));
}
to add a space between each character
return Character.toUpperCase(str.charAt(0))
+ " " + toUpper(str.substring(1));