Why can't I replace \n in a given String? - java

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?

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.

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");
}

try to Replace() method instead of ReplaceAll()
String newString = oldString.replace("\\n", " ");
may be it work for u

String newString = oldString.replace("\n", " ");

Related

How to replace " with blank in a string in java?

I have this string "Distrik Timur". I want to remove " from this string.
I thought String value = translatedValue.replace(""","") will work.But its not working.
Quotation marks need to be escaped: write translatedValue.replace("\"", "").

Replace space digit " " to another

I am looking for a solution concerning replacing space digits into another, for example:
"My Example is interesting".replaceAll(" ", "1");
does NOT return "My1Example1is1interesting", but only "My"
I was looking for solutions also on StackOverflow, but usually found "Removing whitespaces from String/URL.." etc.
Scanner s = new Scanner(System.in);
String in = s.next();
in = in.replaceAll("//s+", "1");
System.out.println(in);
The actual issue is the way in which you are reading data. Scanner.next() reads only one word at a time. SO if your print the value which is read, it is actually "My". use nextLine() to read the entire line.
print in and check what it prints. It should print My i.e, only one word and not words separated by space.
Remember that String object is immutable in Java, you should assign the result to a new String:
String res = "My Example is interesting".replaceAll(" ", "1");
Also note that because String#replaceAll accepts a regex as the first parameter, you can improve the regex by having \\s+ which will work on strings that have more than one or more spaces:
String res = "My Example is interesting".replaceAll("\\s+", "1");
Update: After you posted your code, the problem is not with replaceAll, you should use nextLine instead of next because next reads only the first complete token.
You have to assign the result to another variable.
String s = "My Example is interesting";
String result = s.replaceAll(" ", "");
This will remove spaces.
If you wan to replace with another text.
String result = s.replaceAll(" ", "My Text");

Remove curly brace in Java

I have a text file in which each line begins and ends with a curly brace:
{aaa,":"bbb,ID":"ccc,}
{zzz,":"sss,ID":"fff,}
{ggg,":"hhh,ID":"kkk,} ...
Between the characters there are no spaces. I'm trying to remove the curly braces and replace them with white space as follows:
String s = "{aaa,":"bbb,ID":"ccc,}";
String n = s.replaceAll("{", " ");
I've tried escaping the curly brace using:
String n = s.replaceAll("/{", " ");
String n = s.replaceAll("'{'", " ");
None of this works, as it comes up with an error. Does anyone know a solution?
you cannot define a String like this:
String s = "{aaa,":"bbb,ID":"ccc,}";
The error is here, you have to escape the double quotes inside the string, like this:
String s = "{aaa,\":\"bbb,ID\":\"ccc,}";
Now there will be no error if you call
s.replaceAll("\\{", " ");
If you have an IDE (that is a program like eclipse), you will notice that a string is colored different from the standard color black (for example the color of a method or a semicolon [;]). If the string is all of the same color (usually brown, sometimes blue) then you should be ok, if you notice some black color inside, you are doing something wrong. Usually the only thing that you would put after a double quote ["] is a plus [+] followed by something that has to be added to the string. For example:
String firstPiece = "This is a ";
// this is ok:
String all = s + "String";
//if you call:
System.out.println(all);
//the output will be: This is a String
// this is not ok:
String allWrong = s "String";
//Even if you are putting one after the other the two strings, this is forbidden and is a Syntax error.
String.replaceAll() takes a regex, and regex requires escaping of the '{' character. So, replace:
s.replaceAll("{", " ");
with:
s.replaceAll("\\{", " ");
Note the double-escapes - one for the Java string, and one for the regex.
However, you don't really need a regex here since you're just matching a single character. So you could use the replace method instead:
s.replace("{", " "); // Replace string occurrences
s.replace('{', ' '); // Replace character occurrences
Or, use the regex version to replace both braces in one fell swoop:
s.replaceAll("[{}]", " ");
No escaping is needed here since the braces are inside a character class ([]).
Just adding to the answer above:
If somebody is trying like below, this won't work:
if(values.contains("\\{")){
values = values.replaceAll("\\{", "");
}
if(values.contains("\\}")){
values = values.replaceAll("\\}", "");
}
Use below code if you are using contains():
if(values.contains("{")){
values = values.replaceAll("\\{", "");
}
if(values.contains("}")){
values = values.replaceAll("\\}", "");
}

Removing space from Java string doesn't work

String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
I have tried
input.replaceAll(" ", "");
input.trim();
Both did not remove white space from the string
Want the string to look like
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
Thanks
Note that the String methods return a new String with the transformation applied. Strings are immutable - i.e. they can't be changed. So it's a common mistake to do:
input.trim();
and you should instead assign a variable:
String output = input.trim();
Following works fine for me:
String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
input = input.replaceAll(" ", "");
System.out.println(input);
Output
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
Strings are immutable, I strongly suspect you are not assigning the string again after replaceAll (or) trim();
One more thing, trim doesn't remove spaces in middle, it just removes spaces at end.
input.replaceAll("\s","") should do the trick
http://www.roseindia.net/java/string-examples/string-replaceall.shtml
String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
input = input.replaceAll(" ", "");
System.out.println(input);
Result:
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
However, replaceAll takes Regular Expression as input value (for replacement) and this case covers getting rid of spaces in variable.
So, if you want to simply get rid of spaces in your String, use input = input.replace(" ", "") to be more efficient.

Replace new line/return with space using regex

Pretty basic question for someone who knows.
Instead of getting from
"This is my text.
And here is a new line"
To:
"This is my text. And here is a new line"
I get:
"This is my text.And here is a new line.
Any idea why?
L.replaceAll("[\\\t|\\\n|\\\r]","\\\s");
I think I found the culprit.
On the next line I do the following:
L.replaceAll( "[^a-zA-Z0-9|^!|^?|^.|^\\s]", "");
And this seems to be causing my issue.
Any idea why?
I am obviously trying to do the following: remove all non-chars, and remove all new lines.
\s is a shortcut for whitespace characters in regex. It has no meaning in a string. ==> You can't use it in your replacement string. There you need to put exactly the character(s) that you want to insert. If this is a space just use " " as replacement.
The other thing is: Why do you use 3 backslashes as escape sequence? Two are enough in Java. And you don't need a | (alternation operator) in a character class.
L.replaceAll("[\\t\\n\\r]+"," ");
Remark
L is not changed. If you want to have a result you need to do
String result = L.replaceAll("[\\t\\n\\r]+"," ");
Test code:
String in = "This is my text.\n\nAnd here is a new line";
System.out.println(in);
String out = in.replaceAll("[\\t\\n\\r]+"," ");
System.out.println(out);
The new line separator is different for different OS-es - '\r\n' for Windows and '\n' for Linux.
To be safe, you can use regex pattern \R - the linebreak matcher introduced with Java 8:
String inlinedText = text.replaceAll("\\R", " ");
Try
L.replaceAll("(\\t|\\r?\\n)+", " ");
Depending on the system a linefeed is either \r\n or just \n.
I found this.
String newString = string.replaceAll("\n", " ");
Although, as you have a double line, you will get a double space. I guess you could then do another replace all to replace double spaces with a single one.
If that doesn't work try doing:
string.replaceAll(System.getProperty("line.separator"), " ");
If I create lines in "string" by using "\n" I had to use "\n" in the regex. If I used System.getProperty() I had to use that.
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
You May use first split and rejoin it using white space.
it will work sure.
String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
L = L+" "+Larray[i];
}
This should take care of space, tab and newline:
data = data.replaceAll("[ \t\n\r]*", " ");

Categories

Resources