[Solved] How to convert every other character to upper case in a string [closed]


If you want to get the uppercase of a char, you should use Character.toUpperCase(c), not String’s toUpperCase.

So, I think you might be looking for something like this:

public static void main(String[] args) {
    String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
    System.out.println(alphabet);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < alphabet.length(); i++) {
        char c = alphabet.charAt(i);
        sb.append(i % 2 == 0 ? Character.toUpperCase(c) : c);
    }
    String result = sb.toString();
    System.out.println(result);
}

Output:

abcdefghijklmnopqrstuvwxyzåäö

AbCdEfGhIjKlMnOpQrStUvWxYzÅäÖ

Since Strings are immutable, you have to create a new String to get what you want. An efficient way of doing this is with a StringBuilder.

Edit:

Another way to do it without StringBuilder and perhaps a more intuitive way is to convert the String to an array of chars, which makes it mutable. In the end, you just convert it back to a String. The result would look like this:

public static void main(String[] args) {
    String alphabet = "abcdefghijklmnopqrstuvwxyzåäö";
    System.out.println(alphabet);

    char[] chars = alphabet.toCharArray();
    for (int i = 0; i < alphabet.length(); i+=2) {
        chars[i] = Character.toUpperCase(chars[i]);
    }
    String result = new String(chars);
    System.out.println(result);
}

4

solved How to convert every other character to upper case in a string [closed]