tags:

views:

55

answers:

2

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
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
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 StringBuilder and append() to it for better performance.
  • You can iterate the string from 0 to length() and check if i == 0 (beginning of string) or, with charAt(..) whether the previous is a space (charAt(i-1) == ' ')
  • for those cases use Character.toUpperCase(c). Append each char to the StringBuilder, either the original, or the capitalized one.
  • finally call toString() of the StringBuilder to get the desired capitalized String

That way, for "james a. gosling" you will get "James A. Gosling"

Bozho