• Post Reply Bookmark Topic Watch Topic
  • New Topic

Capitalize first letter in string  RSS feed

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've googled and googled and can not find an answer. What I am trying to do is take a 'String last' and capitalize the first letter of the string. I tried doing something like this but can't seem to extract and capitalize and then place back the first letter. Obviously there is a piece missing. Can you help me fill it out?

Thanks.


 
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how do I pull the first letter of last and add it to this?

Like any other methods, you assign the method's return value to a variable. Like you did when you called substring.

(be careful, you are using "first" instead of "last")
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rene, I didn't see the declaration of your variable firstLetter, I suppose that you just don't include it in the post. Anyway, in order to obtain the first letter, you should do almost the same thing you do in order to obtain the substring for lastPart. The difference is that now, you want only the first letter, so you must specify that by using a beginIndex and lastIndex.

Then your code is almost the same, just remember to assign the new value to firstLetter after you capitalize it:


Hope it helps!
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hope this help.
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer the following:
This creates one less String object.
 
Siva Arun
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rob,

I agree
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using String rather than StringBuilder?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have thought about that but wasn't sure about the overal performance in created objects. So let's check that out:
So yes, using StringBuilder directly is more efficient and is easier to grasp, since it allows you to actually replace characters (unlike String).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!