-1

As a java beginner, I'm trying to complete a simple exercise to remove all instances of the character 'a' from every element in an array of strings, and then print all elements.

The below code, simply outputs the array unchanged (still containing a's).

I believe I've found an alternative method of achieving it, but I still can't see why the below fails, and for learning purposes would like to know. Any advice would be appreciated.

public static void main(String[] args) {
    String instruments[] = {"cello", "guitar", "violin", "double bass"};

    for (int i = 0; i < instruments.length; i++) {
        String str = instruments[i];

        for (int b = 0; b < str.length(); b++) {
           char a = str.charAt(b);

           if (str.charAt(b) == 'a') {
              str.replace("a", "");
           }
        }
        System.out.println(str);
    }
}
WeSt
  • 2,628
  • 5
  • 22
  • 37
javapalava
  • 711
  • 1
  • 6
  • 15
  • 1
    Strings are immutable. Every modification on a String returns a new String. So you need to reassign the result of replace – Alexis C. Jan 02 '15 at 18:01

2 Answers2

3

String.replace returns the new string. In the snippet above the return value is never used. Try something like this:

instruments[i] = str.replace("a", "");

Also there is no need check whether the string str contains 'a', just do a replace as it will do nothing if the needle ('a') is not found, just as you would expect. This in turn makes the inner loop excess and can be removed. In the end you'd have something like this:

for (int i = 0; i < instruments.length; i++) {
    instruments[i] = instruments[i].replace("a", "");
} 
vidstige
  • 12,492
  • 9
  • 66
  • 110
0

Here is the solution: Remember: String objects are immutable!

public static void main(String[] args) {

String instruments[] = {"cello", "guitar", "violin", "double bass"};

for (int i = 0; i < instruments.length; i++) {
    instruments[i] = instruments[i].replace("a", "");
    System.out.println(instruments[i]); 
    }
}
ProgrammingIsAwsome
  • 1,109
  • 7
  • 15