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;
}
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With