简体   繁体   中英

How do i Increment Char Type for a String in Java?

This works with a single character But i want to do it with a string, i have no idea how to do it.

class test
{
    public static void main(String arg[])
    {
        char c = 'A';
        c = c + 1;
        System.out.println(c);
    }
}

Suppose the String is "Hello World"
so the +1 increment would return "Ifmmp xpsme"

You have to split the String into an array of chars and then add 1 to each char:

public String sumToCharsAtString(String word) {
    StringBuffer b = new StringBuffer();
    char[] chars = word.toCharArray();
    for (char c : chars) {
        if(c != ' ')
            c = (char) (c + 1);
        b.append(c);
    }
    return b.toString();
 }

You really dont need to use the StringBuffer , but in order to save memory , its a really good practice.

It sounds as if you want only alphabetic characters to be incremented. If so, this should work as a general solution (assuming a non-null String):

public String incrementChars(String s) {
    StringBuilder result = new StringBuilder(s.length());
    for (char c : s.toCharArray()) {
        if (Character.isAlphabetic(c)) {
            result.append((char) (c + 1));
        } else {
            result.append(c);
        }
    }
    return result.toString();
}

Note that if performance if especially important, you might be better off with an old-style for-loop that avoids the toCharArray call. But it's unlikely to matter.

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