Capitalise first letter in String

Scamparelli picture Scamparelli · Mar 6, 2013 · Viewed 33.9k times · Source

I'm having trouble converting the first letter to Capital in a String:

rackingSystem.toLowerCase(); // has capitals in every word, so first convert all to lower case
StringBuilder rackingSystemSb = new StringBuilder();
rackingSystemSb.append(rackingSystem);
rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0))); 
rackingSystem = rackingSystemSb.toString();

This doesn't seem to work..

Any suggestions?

Answer

A--C picture A--C · Mar 7, 2013

Try doing:

rackingSystem = rackingSystem.toLowerCase();

Instead of:

rackingSystem.toLowerCase(); 

Strings are immutable, you must reassign the result of toLowerCase().

Easier though, (as long as your String is larger than length 2):

rackingSystem = rackingSystem.substring(0,1).toUpperCase() + rackingSystem.substring(1).toLowerCase();