I have this Java function that’s supposed to convert the string s to title case. It should return a copy of s to the caller, leaving s preserved.
Currently, rv ends up as an empty string. Can anyone tell me why?
private static String titleCase(String s) {
String rv = new String();
StringTokenizer strtok = new StringTokenizer(s);
// handle the potential null error: (should really output a runtime warning here)
if(s == null) return null;
while(strtok.hasMoreTokens()) {
String word = strtok.nextToken();
String firstLetter = word.substring(0,1);
String restOfWord = word.substring(1);
rv.concat(firstLetter.toUpperCase() + restOfWord.toLowerCase());
}
return rv;
}
Strings being immutable in Java, once you have declared rv as “” (= new String()) it won’t change unless you allocate a new String to it.
You can either replace the concat line by:
Or better, use a StringBuilder instead of a String (not tested):