wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Converting a String to uppercase? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting a String to uppercase?" Watch "Converting a String to uppercase?" New topic

Converting a String to uppercase?

Jamie Cotton

Joined: Nov 12, 2004
Posts: 16
Hiya All

If I have a String such as String temp = "this is an example" How do I convert the start of each of the words within the string to uppercase so the output would be "This Is An Example"?

Any help would be greatfull

Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
Why don't you capitalize the first letter and then read through the string and each time you find a blank space, capitolize the NEXT letter
marc weber

Joined: Aug 31, 2004
Posts: 11343

I don't know of any existing methods for this, so I guess I would index through each char in the String and check to see if it's a space or lowercase char. Finding a space would set a flag allowing the next character to be converted to uppercase if needed. (This should initially be set to true in order to allow the first letter to be capitalized.)

Note that chars can be treated as numeric values (although you'll need to cast back to type char after performing arithmetic on them). Uppercase letters A-Z are represented by numeric values 65-90, and lowercase (a-z) are represented by 97-122. So if you have a lowercase value, you can convert it to uppercase by subtracting 32. (Ensure first that the char you have is, in fact, within that lowercase range.) A space is represented by 32.

Ref: http://www.lookuptables.com/

To avoid creating numerous String objects, you might want to use a StringBuffer (or StringBuilder in Java 1.5).
[ April 06, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Andy Donatelo

Joined: Mar 31, 2005
Posts: 1
Consider using a StringTokenizer to break your String based on the � � (empty space) and capitalize the first letter of each token.

Joel McNary

Joined: Aug 20, 2001
Posts: 1815
...or the String.split() method (1.4+ ), instead of a StringTokenizer.

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Jamie Cotton

Joined: Nov 12, 2004
Posts: 16
Hiya thankyou all for your input i have now managed to do it

jQuery in Action, 2nd edition
subject: Converting a String to uppercase?
Similar Threads
Scanner string parameters
Writing a GUI program
First letter of every word to be in capital
Find String that contains a given substring ignoring case
Using simultaneously Converters