Why is replaceAll() not working?

edited October 2015 in Questions about Code

In the following code, testDoc.txt is comprised of the single word 'Johnson'. Why is my output 'Johnson' and not 'Wilson'?

String [] doc = loadStrings("testDoc.txt");
String name = "Wilson";

for (int i=0; i<doc.length; i++) { 
  doc[i].replaceAll("Johnson", name);
}

print(doc);

Answers

  • Answer ✓

    It is. But you aren't assigning the result anywhere. It doesn't change the string in-place, it's created a new string.

  • Thanks, koogs. I've devised the following as a solution. Is there a better way? Or a way to change the string in-place?

    String [] doc = loadStrings("testDoc.txt");
    String [] newDoc = {""};
    String name = "Wilson";
    String strg = "";
    
    for (int i=0; i<doc.length; i++) { 
      strg = doc[i].replaceAll("Johnson", name) + "\n";
      newDoc = append(newDoc, strg); 
    }
    
    print(newDoc);
    
  • Answer ✓

    you can assign it to itself:

    doc[i] = doc[i].replaceAll("Johnson", name);

    Using replace() instead of replaceAll() should be slightly faster, but if you don't have a huge file, it should not be relevant.

  • Thanks, benja. That does the trick.

  • you can, as, benja says, assign it to itself, it that's not a problem.

    otherwise, you know the size of the output array is the same as the input array so allocate an array of that size and then fill it in.

    append() is terrible in memory allocation terms, i wouldn't recommend using it.

    replace() does something else entirely, swaps one letter for another. its not what you need. maybe benja meant replaceFirst() which does substrings but only the first instance.

  • replace() does something else entirely, swaps one letter for another. its not what you need. maybe benja meant replaceFirst() which does substrings but only the first instance.

    I meant replace() and it actually works with substrings too:

    docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29

    But replaceAll() works with regex, which can be very useful.

  • Again, thanks to both for the input.

Sign In or Register to comment.