简体   繁体   中英

Java and incrementing strings

I have

String sth = "abc";

and would like to increment it in Java. So I would like to have a loop SIMILAR to the one below:

for (int i = 0; i < 50; i++) {
    System.out.println(sth++);
}

to have output

abc
abd
abe
abf
...
aby
abz
aca
acb

etc

Is there a way to do that in Java?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM