i need to convert the first letter of a string of names to uppercase and using the charat method but not sure how to use the char at method
+2
A:
I'm not really sure on how charAt() could be really useful in your case, but you can try this :
String s = "yourString";
char firstCharInUpperCase = Character.toUpperCase(s.charAt(0));
String yourNewString = new StringBuilder(s).setCharAt(0, firstCharInUpperCase).toString();
Resources :
Colin Hebert
2010-09-12 19:26:05
i have a string of names that is lowercase and need to convert the first letter to uppercase so i was trying to use the charat to get the first letter and convert it to uppercase
shep
2010-09-12 19:28:02
A:
Some points:
- Strings are immutable - i.e. you can't change their internal char array. So you have to make as many new strings as changes you perform on them. So better use a
StringBuilderandappend()to it for better performance. - You can iterate the string from 0 to
length()and check ifi == 0(beginning of string) or, withcharAt(..)whether the previous is a space (charAt(i-1) == ' ') - for those cases use
Character.toUpperCase(c). Append each char to theStringBuilder, either the original, or the capitalized one. - finally call
toString()of theStringBuilderto get the desired capitalizedString
That way, for "james a. gosling" you will get "James A. Gosling"
Bozho
2010-09-12 19:30:39