0

I have a question in regards to replacing certain characters. I have a string of x amount of characters, within which they contain all characters within the normal English alphabet.

String x = "exampleString"

My question is, because what i want to do is replace the characters that are within this string, I'm not able to user replace, as this replaces previously replaces strings, such as.

if(x.contains(e)){
x = x.replace("e","a")
}

That will replace every E character within the string above.

I was also trying to use:

x=x.replace("e","a").replace("a","b") 

but that would also replace every a character, even the previously replaced. I though this would work, because strings are immutable in Java, however it doesn't.

I also considered counter to see when the string has been replaced and omit the replaced strings, however I'm not able to implement this.

Can anyone suggest solution?

Regards ProgrammingNewbie.

shmosel
  • 49,289
  • 6
  • 73
  • 138

2 Answers2

1

You can try this:

 // Your String
String str = "exampleString";

// Convert it to a Character array.
char[] strCharArr = str.toCharArray();

// Have a corresponding boolean array
boolean[] arrStr = new boolean[str.length()];

// Character to be replaced
char a = 'r';

// Character to be replaced with
char b = 's';        

// Loop through the array
for(int i = 0; i < strCharArr.length; i++) {

    // Check if the characted matches and have not been replaced before.
    if(strCharArr[i] == a && !arrStr[i]) {
        strCharArr[i] = b;
        arrStr[i] = true; 
    }
}
System.out.println(String.valueOf(strCharArr));

// Now if you need to replace again. 
a = 's';
b = 'a';        
for(int i = 0; i < strCharArr.length; i++) {
    if(strCharArr[i] == a && !arrStr[i]) {
       strCharArr[i] = b;
       arrStr[i] = true; 
    }
}

System.out.println(String.valueOf(strCharArr));

After this you can convert back the character array to the corresponding string. You can write a function and replace it as many times you want.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
0

The problem is that you are performing two replacements over the entire string, subjecting a position to multiple replacements. You need a solution that loops over the string only once, so that an "e" that is replaced with "a" won't then get replaced with a "b".

String x = "exampleString";
StringBuilder buf = new StringBuilder(x);
for (int i = 0; i < buf.length(); i++)
{
    switch (buf.charAt(i))
    {
    case 'e':
        buf.setCharAt(i, 'a');
        break;
    case 'a':
        buf.setCharAt(i, 'b');
        break;
    }
}
System.out.println(buf.toString());

This uses a StringBuilder for mutability and it bypasses the replace method. There is no need to keep track of what has been replaced. This will only perform a maximum of one replacement per character. Output when run:

axbmplaString
rgettman
  • 176,041
  • 30
  • 275
  • 357