大写首字母串[复制](Capitalise first letter in String [dupl

2019-08-17 09:10发布

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

  • 如何利用Java中的字符串的第一个字母? 47个回答

我无法转换的第一个字母,以资本的字符串:

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

这似乎并没有工作..

有什么建议?

Answer 1:

尝试这样做:

rackingSystem = rackingSystem.toLowerCase();

代替:

rackingSystem.toLowerCase(); 

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

虽然容易,(只要你的字符串短长度2大):

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


Answer 2:

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


文章来源: Capitalise first letter in String [duplicate]