Reputation: 1794
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);
Upvotes: 1
Views: 369
Reputation: 4999
str.replace(str.charAt(i), '*');
will replace all characters. Javadoc
You can use a StringBuilder to replace a specific character in a String. Please review this question and answer.
Replace a character at a specific index in a string?
Upvotes: 0
Reputation: 1503649
In each case, the if
part just finds whether the character should be replaced... but then the replacement itself:
str = str.replace(str.charAt(i), '*')
... 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:
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == '-' && Character.isDigit(chars[i + 1])) {
chars[i] = '*';
}
// Similarly for the other two
}
String newString = new String(chars);
Or to avoid the duplication, replace the middle section with:
for (int i = 0; i < chars.length - 1; i++) {
if (Character.isDigit(chars[i + 1]) &&
(chars[i] == '-' || chars[i] == 'e' || chars[i] == '.')) {
chars[i] = '*';
}
}
Upvotes: 3