views:

44

answers:

2

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

+1  A: 
/**
 * returns the string, the first char lowercase
 *
 * @param target
 * @return
 */
public final static String asLowerCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toLowerCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}

/**
 * returns the string, the first char uppercase
 *
 * @param target
 * @return
 */
public final static String asUpperCaseFirstChar(final String target) {

    if ((target == null) || (target.length() == 0)) {
        return target; // You could omit this check and simply live with an
                       // exception if you like
    }
    return Character.toUpperCase(target.charAt(0))
            + (target.length() > 1 ? target.substring(1) : "");
}
Pentium10
my problem was so trivial its all about null string
yoav.str
A: 

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.

polygenelubricants