Search code examples
javastringcharacteruppercaselowercase

Convert java char inside string to lowerCase/upperCase


I have a String called "originalstring" which contains a sentence with mixed upper and lower case characters.

I simply want to flip the string so that if a character is a lowercase make it upper case and vice versa and return it.

I have 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. Also, this means that your for loop will never get to the end of the iteration of the for loop, because originalString.length() changes each loop also. It's an infinite loop.

    Instead, create a StringBuilder that stores the converted characters as you're iterating over the original string. The convert it to a 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();