Basically I want to recursively get this:
“ pErHaPs I hAVe wRitten a Sentence LiKE this one “
To look like this:
“perhapsIHaveWrittenASentenceLikeThisOne”
What I think I understand:
string.charAt(i)
to compare the specific character to a space Character.isUpperCase()
for case checking What I don't understand:
How recursion will work to change the string since strings are immutable
What the base case will be
how to only uppercase the first letter of every word after the first word
EDIT: This is what I have come up with after a few helpful hints: `public static String toCamelCase(String str) {
if(str.length() == 1) {
if(str.charAt(0) == ' ') {
return "";
} else {
return str;
}
} else if(str.charAt(0) == ' ' && str.length() != 1) {
if(str.charAt(1) != ' ') {
return str.substring(1, 2).toUpperCase() + toCamelCase(str.substring(2, str.length()));
} else {
return toCamelCase(str.substring(1, str.length()));
}
} else if(str.charAt(0) != ' ' && str.length() != 1) {
if(str.charAt(1) != ' ') {
return str.substring(0,2).toLowerCase() + toCamelCase(str.substring(2, str.length()));
} else {
return str.substring(0,1).toLowerCase() + toCamelCase(str.substring(1, str.length()));
}
}
return str;
}`
Everything works except the first letter of the first word is also capitalized. How would I make the code exclude the first word when uppercasing first letters of words? Is this possible recursively?
There you go with your recursive implementation:
public String camelCase(String inputStr) {
String s = inputStr.toLowerCase();
String[] arr = s.split(" ");
s = arr[0];
return getCamelCased(s,1,arr);
}
private String getCamelCased(String s, int index, String[] arr) {
if(index >= arr.length)
return s;
String curr = arr[index++];
s += curr.length()==1?curr.toUpperCase():
(curr.toUpperCase.charAt(0)+curr.substring(1,curr.length()));
return getCamelCased(s,index,arr);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.