Capitalise first letter in String [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-05 08:44:41

问题


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?


回答1:


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();



回答2:


StringBuilder rackingSystemSb = new StringBuilder(rackingSystem.toLowerCase());
rackingSystemSb.setCharAt(0, Character.toUpperCase(rackingSystemSb.charAt(0)));
rackingSystem = rackingSystemSb.toString();


来源:https://stackoverflow.com/questions/15259774/capitalise-first-letter-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!