Is there a built in function to do title-case for you or will I have to write a custom function? I'm attempting to title-case a full name.
I.E. john doe should be converted to: John Doe
Is there a built in function to do title-case for you or will I have to write a custom function? I'm attempting to title-case a full name.
I.E. john doe should be converted to: John Doe
The simplest code I can figure out at the moment:
String str = "mR. jOhn smIth";
final String[] arr = TextUtils.split(str," ");
final int len = arr.length;
for(int i = 0; i < len; i++)
{
final String s = arr[i];
final String s0 = "" + s.toUpperCase().charAt(0);
final String s1 = s.toLowerCase().substring(1, s.length());
arr[i] = s0 + s1;
}
str = TextUtils.join(" ", arr); // and now str contains "Mr. John Smith"
No it does'nt exist in the official Android API, but it's pretty easy to wrote your own one. Something like this:
public static String camelCasedString(String s){
boolean shouldCapitalize = true;
char[] arr = s.toCharArray();
for(int i = 0; i < arr.length; i++){
if(arr[i] == ' '){
shouldCapitalize = true;
} else if(shouldCapitalize){
arr[i] = Character.toUpperCase(arr[i]);
shouldCapitalize = false;
} else {
arr[i] = Character.toLowerCase(arr[i]);
}
}
return new String(arr);
}
Output:
System.out.println(camelCasedString("john dOe")); //John Doe
System.out.println(camelCasedString("john doe")); //John Doe
System.out.println(camelCasedString("John Doe")); //John Doe
System.out.println(camelCasedString("JOHN DOE")); //John Doe
You haven't said what language so I'll just assume javascript. The most compact way I know of doing it is:
String.prototype.titleCase = function() {
t = this.split(' ').map((word) => word.charAt(0).toUpperCase()+word.slice(1)).join(' ');
return t;
}
Since I've declared the function on the String.prototype, you can use it thus:
"This is a title".titleCase() // >> "This Is A Title"
which may not be 100% the way newspaper editors would have it, but it does what you seem to want it to do. Let me know if you need further explanation.