a.replace(d, changed)
replaces every occurrence of d
in the string, not just the one at the index you are looking at.
- So for every letter that occurs an even number of times in the string, the replace of that letter is performed an even number of times, leaving all occurrences at the same case that the first occurrence had from the outset. This was what happened to
o
, for example. When you met the first o
, both occurrences were replaced to upper case O
. When you met the next O
, it was already upper case, so both occurrences were changed to lower case again.
- Conversely if a letter occurs an odd number of times, it will through the same procedure be left at the opposite case of what the first occurrence had from the outset. From the outset you had
e
twice and E
once. First the two lower case e
were changed to upper case. Second alll three were changed to lower case. Third, all to upper case.
Instead do not perform the replacements directly in the string. Use either a StringBuffer
or StringBuilder
or a char
array. In each of these you can perform the replacement by index so that you are only affecting the occurrence of the letter that you intend to affect.
Bonus tip: if (letter == true)
is considered mediocre style. Prefer just if (letter)
.
Bonus information: Letters exist that become more than one letter when switching case. If I enter the German word Füße
(feet), ß
only exists in lower case, it becomes SS
in upper case. So the correct reverse of the word would be fÜSSE
. However, Character.toUpperCase()
cannot return two chars, so just leaves it at ß
.