在字符串中首字母大写[重复]

时间:2021-02-19 18:08:38

This question already has an answer here:

这个问题在这里已有答案:

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

我在将字符串中的第一个字母转换为Capital时遇到问题:

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?

2 个解决方案

#1


68  

Try doing:

rackingSystem = rackingSystem.toLowerCase();

Instead of:

rackingSystem.toLowerCase(); 

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

字符串是不可变的,您必须重新分配toLowerCase()的结果。

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

但是更容易(只要你的String大于长度2):

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

#2


18  

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

#1


68  

Try doing:

rackingSystem = rackingSystem.toLowerCase();

Instead of:

rackingSystem.toLowerCase(); 

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

字符串是不可变的,您必须重新分配toLowerCase()的结果。

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

但是更容易(只要你的String大于长度2):

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

#2


18  

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