'Result of Replace function isn´t used / cannot be applied
I want to iterate over two input strings that being stored in an array. Next, I want to replace all umlauts (ä,ö,ü, ...) by its "aquivalents" a,o,u. Somehow the changes seem to not be applied to the array. How´s that possible and what to do in order to fix this? Thaanks for helping me!!!
String[] liste = {wort1, wort2};
for(int i =0; i<2; i++) {
for (int j=0; j<liste[i].length(); j++) {
String buchstabe = liste[i].substring(j,j+1);
switch(buchstabe) {
case "ä":
case "Ä":
buchstabe.replace("ä", "a");
break;
case "ö":
case "Ö":
buchstabe.replace("ö", "o");
break;
case "ü":
case "Ü":
buchstabe.replace("ü", "u");
break;
case "ß":
buchstabe.replace("ß", "ss");
break;
default:
break;
Solution 1:[1]
Strings in are immutable in Java, so you can't change a string.
The replace method creates a new strings and returns it, so you'll need to set the buchstabe variable to the newly created string:
buchstabe = buchstabe.replace("ä", "a");
BTW.: You don't need to go through each character individually, the replace method replaces all occurrences in a string.
The replace method does not care whether the needle is present in your haystack. Therefore you can also save the checks whether e.g. an "ä" is contained in your string:
String[] liste = {wort1, wort2};
for(int i = 0; i < liste.length; i++) {
liste[i] = liste[i].replace("ä", "a");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
