-1

My friend is trying to finish his Computer Science project but one thing is preventing him from doing that: the String method replaceAll doesn't seem to be working correctly. He wants to remove all the instances of new line or a return (\n or a \r) and replace them with a couple spaces.

for(int c = 0; c<bible.size(); c++){
    bible.get(c).getForeign().replaceAll("\\n","          ");
    bible.get(c).getForeign().replaceAll("\\r","          ");
}

the code

bible.get(c).getForeign()

returns a String in a different language that is read in from a text file. Is there anything wrong with this code? It doesn't seem to replace the new lines with spaces. I checked the JavaDocumentation on the String class and for the

replaceAll(String str, String replacement);

they said that backslashes and dollar signs might make the returned string a little different. Is there another way to do this? Thanks in advance.

bob
  • 3,917
  • 2
  • 18
  • 28
Cal Dilworth
  • 123
  • 1
  • 8

1 Answers1

0

String objects are immutable. The results are not stored in the original object. replaceAll() returns a String object which you can store back like follows:

bible.get(c).setForeign(bible.get(c).getForeign().replaceAll("\\n","          "));
Sujeet Sinha
  • 2,152
  • 2
  • 14
  • 22
  • *How* did you manage to post an answer after the question was closed!? :O – luk2302 Jun 29 '16 at 17:13
  • Thats really strange co-incidence!! I started writing the answer when I saw the post. By the time I clicked 'Post Answer', it was closed but the answer was submitted.. Very rare occurence of this phenomenon!! :) – Sujeet Sinha Jun 29 '16 at 17:15
  • @luk2302 There is a grace period where it is still possible to post after closure. [It is actually quite long](http://meta.stackoverflow.com/questions/252711/this-answer-was-posted-after-the-question-was-closed-how-is-that-possible). – Tunaki Jun 29 '16 at 17:17
  • @Tunaki thanks.. i wasn't aware of any grace period! – Sujeet Sinha Jun 29 '16 at 17:19