On String being immutable
Regarding your first attempt:
String s = gameList[0].toString();
s.replaceFirst(...);
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:
s1.trim();
s2.replace("x", "y");
Instead, you'd want to do something like this:
s1 = s1.trim();
s2 = s2.replace("x", "y");
As for changing the first letter of a CharSequence
to uppercase, something like this works (as seen on 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"
}
This of course will throw NullPointerException
if s == null
. This is often an appropriate behavior.