Format name in title case Java help please?

Mohammed Ahmed picture Mohammed Ahmed · Sep 30, 2012 · Viewed 16.9k times · Source

so i have to write a java code to :

  • Input a name
  • Format name in title case
  • Input second name
  • Format name in title case
  • Display them in alphabet order

i know that The Java Character class has the methods isLowerCase(), isUpperCase, toLowerCase() and toUpperCase(), which you can use in reviewing a string, character by character. If the first character is lowercase, convert it to uppercase, and for each succeeding character, if the character is uppercase, convert it to lowercase.

the question is how i check each letter ? what kind of variables and strings should it be contained ? can you please help?

Answer

Rohit Jain picture Rohit Jain · Sep 30, 2012

You should use StringBuilder, whenver dealing with String manipulation.. This way, you end up creating lesser number of objects..

StringBuilder s1 = new StringBuilder("rohit");
StringBuilder s2 = new StringBuilder("jain");

s1.replace(0, s1.length(), s1.toString().toLowerCase());
s2.replace(0, s2.length(), s2.toString().toLowerCase());            

s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));
s2.setCharAt(0, Character.toTitleCase(s2.charAt(0)));

if (s1.toString().compareTo(s2.toString()) >= 0) {
    System.out.println(s2 + " " + s1);

} else {
    System.out.println(s1 + " " + s2);
}