Link to home
Start Free TrialLog in
Avatar of Ke11ie
Ke11ieFlag for Australia

asked on

Format Input Text in Title Case

The user is promted to input a name. I want to make sure that the formatting is correct - in Title Case.

For example, if the user types in, bob smith, all in lowercase I want java to format it correctly into: Bob Smith - formatted in Title Case.

I am trying to work something out by using StringBuffer...

I may eventually get there, but to speed up the process, you may know something really simple!
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ke11ie

ASKER

I don't really know how to do that... I'm only a "Learner".
String[] words = s.split(" ");
Avatar of Ke11ie

ASKER

So then how to get it to only capitalise the first character of each word?
then use your StringBuuffer to convert each word to title case.
Avatar of Ke11ie

ASKER

I can only convert all words to uppercase or all words to lowercase. Is there a simple way for Title Case? I don't know how to do this.
no there is no simple way, you need to implement it yourself.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ke11ie

ASKER

The for loop does sound like a good idea but i still don't really know how to make it change each of the characters. Do I use something like CharAt(" ") + 1? toUppercase?
Ke11ie,

There is a static toUpperCase() method on the Character class and a setCharAt() method on the StringBuffer class. Use those methods!

\t
>>The for loop does sound like a good idea but i still don't really know how to make it change each of the characters.
>>Do I use something like CharAt(" ") + 1? toUppercase?

1) You have your string you want to title case
2) Have a StringBuffer too (initially empty)
3) Iterate over your string
    with yourString.charAt(i) you can get the character at index i
    with yourString.charAt(i-1) you can get the character at index i-1
    a) if it is the first character of the string : append it its uppercase version to the StringBuffer
         [ Character.toUpperCase(theOriginalCharacter) returns the upper cased character ]
         [ You can append a character by just calling append(yourCharacter) ]
    b) if the previous character (the one at index i-1) is a blank :
        append the uppercase version of the character at index i to the StringBuffer
    c) if it is none of the above cases a) or b) just append the character at index i to the StringBuffer
4) After having iterated through the whole string this way, your StringBuffer contains the title cased version
    of your original string.
You don't need to iterate over the whole string, only the first character needs to be changed.