Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 499
me72921 Avatar asked Feb 12 '26 01:02

me72921


2 Answers

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();
like image 86
rgettman Avatar answered Feb 14 '26 16:02

rgettman


Common-lang provide a swapCase function, see the doc. Sample from the doc:

StringUtils.swapCase(null)                 = null
StringUtils.swapCase("")                   = ""
StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"

And if you really want to do it by yourself, you can check the source of common-lang StringUtils