1

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);
6
  • Perhaps you should write out the contents of str at the end of the for-loop. Then you can see what happens when. Commented Oct 15, 2012 at 22:02
  • 2
    This sounds like exactly what you should expect: it replaces all 'e's with '*'s. Commented Oct 15, 2012 at 22:02
  • 2
    Unrelated you may have an issue if i is the last character and you try to evaluate str.charAt(i+1) Commented Oct 15, 2012 at 22:03
  • Do you want your program fixed, or is it OK to show a simpler solution? Commented Oct 15, 2012 at 22:04
  • Logical ANDs must both be true for the answer to be true though. Commented Oct 15, 2012 at 22:05

2 Answers 2

3

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] = '*';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.