Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method to reverse upper-lower case doesn't reverse all letters

I wanted to create a method that reverse upper-lower case letters in a word. The problem I'm having is that the method doesn't reverse all the letters. For example when I type "nIceToMeEtyoU" it prints "NiCETomEETYou". It didn't work for the "o", the second "e" and "t". I just couldn't figure out what's wrong with the code.

public static String reverseCase(String str) {
    char changed;
    String a = str;
    for (int i = 0; i < a.length(); i++) {
        char d = a.charAt(i);
        boolean letter = Character.isUpperCase(d);
        if (letter == true) {
            changed = Character.toLowerCase(d);
        } else {
            changed = Character.toUpperCase(d);
        }
        a = a.replace(d, changed);
    }
    return a;
}
like image 206
HyperMelon Avatar asked Sep 19 '20 14:09

HyperMelon


2 Answers

String::replace returns a new String with all occurrences of the character you wanted replaced changed.

Also, Strings in Java are immutable, meaning you cannot replace a character in a string while keeping the same string. In order to replace the character at a specific index, see this post

like image 122
Irad Ohayon Avatar answered Sep 22 '22 03:09

Irad Ohayon


It didn't work for the "o","second e" and "t".

The replace() method replaces all occurrances of the character in the string.

Instead, use a StringBuffer to append each character as you iterate through the string.

Then when the loop is finished you recreate the String using the toString() method of the StringBuffer.

like image 36
camickr Avatar answered Sep 19 '22 03:09

camickr