在android中将CharSequence第一个字母更改为大写
它可能看起来很简单,但它有很多错误 我尝试了这种方式:
String s = gameList[0].toString();
s.replaceFirst(String.valueOf(s.charAt(0)),String.valueOf(Character.toUpperCase(s.charAt(0))) );
它抛出了一个异常
我的另一次尝试是:
String s = gameList[0].toString();
char c = Character.toUpperCase(gameList[0].charAt(0));
gameList[0] = s.subSequence(1, s.length());
rhis one也抛出了一个异常
it may seem simple but it posses lots of bugs
I tried this way:
String s = gameList[0].toString();
s.replaceFirst(String.valueOf(s.charAt(0)),String.valueOf(Character.toUpperCase(s.charAt(0))) );
and it throws an exception
another try i had was :
String s = gameList[0].toString();
char c = Character.toUpperCase(gameList[0].charAt(0));
gameList[0] = s.subSequence(1, s.length());
rhis one also throws an Exception
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
。 。 。或者在一个数组中完成这一切。这是类似的东西。
. . . or do it all in an array. Here's something similar.
关于字符串不可变
关于您的第一次尝试:
Java 字符串是不可变的。您不能在字符串实例上调用方法并期望该方法修改该字符串。
replaceFirst
相反返回一个新字符串。这意味着这些类型的用法是错误的:相反,您想做这样的事情:
至于将
CharSequence
的第一个字母更改为大写,类似这样的操作是有效的(如 ideone.com 上所示):如果
s,这当然会抛出
。这通常是一种适当的行为。NullPointerException
== nullOn String being immutable
Regarding your first attempt:
Java strings are immutable. You can't invoke a method on a string instance and expect the method to modify that string.
replaceFirst
instead returns a new string. This means that these kinds of usage are wrong:Instead, you'd want to do something like this:
As for changing the first letter of a
CharSequence
to uppercase, something like this works (as seen on ideone.com):This of course will throw
NullPointerException
ifs == null
. This is often an appropriate behavior.我喜欢使用这个更简单的名称解决方案,其中 toUp 是一个由 (" ") 分割的全名数组:
并且这个修改后的解决方案可用于仅大写完整字符串的第一个字母,同样 toUp 是一个字符串列表:
希望这有帮助。
I like to use this simpler solution for names, where toUp is an array of full names split by (" "):
And this modified solution could be used to uppercase only the first letter of a full String, again toUp is a list of strings:
Hope this helps.