I’m having some troubles the replacement of a character in a string. The code works perfectly fine for the removal of hyphens an periods, however for the letter ‘e’ it removes the ‘e’ in “test”, and it also converts the three ‘e’s at the end of the string. Does anyone know why this is happening?
String str = "This is a test string, 12345! -12e3.0 eee";
for(int i = 0; i < str.length(); i++) {
if((str.charAt(i) == '-') && (Character.isDigit(str.charAt(i+1)))) {
str = str.replace(str.charAt(i), '*');
}
if((str.charAt(i) == 'e') && (Character.isDigit(str.charAt(i+1)))) {
str = str.replace(str.charAt(i), '*');
}
if((str.charAt(i) == '.') && (Character.isDigit(str.charAt(i+1)))) {
str = str.replace(str.charAt(i), '*');
}
}
str = str.replaceAll("[1234567890]", "*");
System.out.println(str);
In each case, the
ifpart just finds whether the character should be replaced… but then the replacement itself:… performs that replacement for the whole of the string.
The simplest fix to this is probably to convert it to an array of characters to start with, replace one character at a time, and then create a string for the rest:
Or to avoid the duplication, replace the middle section with: