[Solved] Java and incrementing strings


You can’t apply the ++ operator to a string, but you can implement this logic yourself. I’d go over the string from its end and handle each character individually until I hit a character that can just be incremented simply:

public static String increment(String s) {
    StringBuilder sb = new StringBuilder(s);

    boolean done = false;
    for (int i = sb.length() - 1; !done && i >= 0; --i) {
        char c = sb.charAt(i);
        if (c == 'z') {
            c="a";
        } else {
            c++;
            done = true;
        }
        sb.setCharAt(i, c);
    }

    if (!done) {
        sb.insert(0, 'a');
    }

    return sb.toString();
}

0

solved Java and incrementing strings