字符串是不可变的
关于您的第一次尝试:
String s = gameList[0].toString();
s.replaceFirst(...);
Java 字符串是不可变的。您不能在字符串实例上调用方法并期望该方法修改该字符串。replaceFirst
而是返回一个新字符串。这意味着这些用法是错误的:
s1.trim();
s2.replace("x", "y");
相反,你想做这样的事情:
s1 = s1.trim();
s2 = s2.replace("x", "y");
至于将 a 的第一个字母更改CharSequence
为大写,类似这样的工作(如在 ideone.com 上所见):
static public CharSequence upperFirst(CharSequence s) {
if (s.length() == 0) {
return s;
} else {
return Character.toUpperCase(s.charAt(0))
+ s.subSequence(1, s.length()).toString();
}
}
public static void main(String[] args) {
String[] tests = {
"xyz", "123 abc", "x", ""
};
for (String s : tests) {
System.out.printf("[%s]->[%s]%n", s, upperFirst(s));
}
// [xyz]->[Xyz]
// [123 abc]->[123 abc]
// [x]->[X]
// []->[]
StringBuilder sb = new StringBuilder("blah");
System.out.println(upperFirst(sb));
// prints "Blah"
}
这当然会抛出NullPointerException
if s == null
。这通常是一种适当的行为。