Convert Java char in string to lowercase / uppercase

I have a string called "original string", which contains a sentence with a mixture of uppercase and lowercase characters

I just want to flip the string so that if a character is lowercase, make it uppercase, and vice versa, and return it

I tried this code, which returns the original string in uppercase:

for (int i = 0; i < originalString.length(); i++) {
        char c = originalString.charAt(i);

        if (Character.isUpperCase(c)) {
            originalString += Character.toLowerCase(c);

        }

        if (Character.isLowerCase(c)) {
            originalString += Character.toUpperCase(c);

        }

    }
    return originalString;

Solution

You are adding characters to the original string In addition, this means that the for loop will never end the iteration of the for loop, because originalstring Length () also changes each loop This is an infinite loop

Instead, create a StringBuilder that stores the converted characters as you iterate over the original string Convert it to string and return it at the end

StringBuilder buf = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
    char c = originalString.charAt(i);

    if (Character.isUpperCase(c)) {
        buf.append(Character.toLowerCase(c));

    }
    else if (Character.isLowerCase(c)) {
        buf.append(Character.toUpperCase(c));

    }
    // Account for case: neither upper nor lower
    else {
        buf.append(c);
    }

}
return buf.toString();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>