• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting a String to uppercase?

 
Jamie Cotton
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Cheers
 
Elouise Kivineva
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Andy Donatelo
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider using a StringTokenizer to break your String based on the � � (empty space) and capitalize the first letter of each token.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...or the String.split() method (1.4+ ), instead of a StringTokenizer.
 
Jamie Cotton
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hiya thankyou all for your input i have now managed to do it

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic