Reputation: 23
I found the question here before but somehow I can't see what I'm doing wrong. So I have a given String that looks something like this:
"Some text here\n\nsome more text here"
And I want to remove the linebreaks and display the Text in a TextView. I tried using String.replaceAll:
String newString = oldString.replaceAll("\\n", " ");
But that didn't change anything in the text. However,
oldString.contains("\\n");
returns true. What am I doing wrong?
edit:
I'm sorry, I know, oldString
doesn't change. The problem is that, if I print oldString
and newString
they're exactly the same even though it says that oldString
does contain a "\n".
This is my code:
Log.d(TAG, "contains: " + str.contains("\\n"));
Log.d(TAG, "old: " + str);
str = str.replaceAll("\\n", " ");
Log.d(TAG, "new: " + str);
And this is what I get:
contains: true
old: Vorgang nicht möglich\n\nBitte Karte entnehmen
new: Vorgang nicht möglich\n\nBitte Karte entnehmen
UPDATE
Thanks to Shivanshu Verma, I tried str.replace("\\n"" ");
instead of str.replaceAll("\\n", " ");
and that works! Does anybody know, why I can't use replaceAll()
here?
Upvotes: 1
Views: 15667
Reputation: 1494
Strings in Java are immutable and as such the new string with the replacements is stored in newString, not oldString.
EDIT
I see now that your issue was not actually related to Java String immutability but rather the difference between replace() and replaceAll(). The difference between these is that replaceAll() takes in a regex as the first argument, which will then replace any matches with the second argument, whereas replace() simply takes in a CharSequence (of which String is an implementation) and will replace exact matches with the second argument.
In your case, I think your original String had the newline characters escaped:
String str = "Vorgang nicht möglich\\n\\nBitte Karte entnehmen";
which meant that the String didn't actually contain newline characters at all; it contained literally "\n"
. This would mean that:
str.replaceAll("\\n", " ");
will resolve the first argument to a regex and replace newline characters (of which there were none), and:
str.replace("\\n", " ");
will replace exact matches of "\n"
. It's also worth noting that as others have pointed out contains() also doesn't take in a regex, which is why running:
oldString.contains("\\n");
returned true.
Upvotes: 15
Reputation: 10051
Your code works perfectly fine.
This test will pass without any error:
@Test
public void testReplaceAll() {
String newString = "line1\nline2\nline3".replaceAll("\\n", " ");
assertThat(newString).isEqualTo("line1 line2 line3");
assertThat(newString).doesNotContain("\\n");
}
Upvotes: 2
Reputation: 601
try to Replace() method instead of ReplaceAll()
String newString = oldString.replace("\\n", " ");
may be it work for u
Upvotes: 1