Reputation: 3
i have a space before a new line in a string and cant remove it (in java). I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
Upvotes: 0
Views: 6669
Reputation: 120506
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll
takes a regular expression as an argument. The [ \t]
matches one or more spaces or tabs. The (\r\n?|\n)
matches a newline and puts the result in $1
.
Upvotes: 3
Reputation: 34534
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Upvotes: 1
Reputation: 8295
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
Upvotes: 1
Reputation: 4207
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}
Upvotes: 0
Reputation: 2739
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
Upvotes: 0
Reputation: 533492
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
Upvotes: 0