我有这样的字符串
"hello
java
book"
Run Code Online (Sandbox Code Playgroud)
我想从字符串中删除\ r和\n(hello\r \n \njava\r \nbook).我想要一个字符串作为"hellojavabook".我怎样才能做到这一点?
Tof*_*eer 125
正则表达式与replaceAll.
public class Main
{
public static void main(final String[] argv)
{
String str;
str = "hello\r\njava\r\nbook";
str = str.replaceAll("(\\r|\\n)", "");
System.out.println(str);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想在成对时删除\ r \n(上面的代码删除了\ r或\n),请执行以下操作:
str = str.replaceAll("\\r\\n", "");
Run Code Online (Sandbox Code Playgroud)
Law*_*Dol 16
如果要避免使用正则表达式,或者必须以较早的JVM为目标,String.replace()将执行以下操作:
str=str.replace("\r","").replace("\n","");
Run Code Online (Sandbox Code Playgroud)
并删除CRLF对:
str=str.replace("\r\n","");
Run Code Online (Sandbox Code Playgroud)
后者比构建正则表达式做同样的事情更有效.但我认为前者将作为正则表达式更快,因为字符串只被解析一次.
小智 14
public static void main(final String[] argv)
{
String str;
str = "hello\r\n\tjava\r\nbook";
str = str.replaceAll("(\\r|\\n|\\t)", "");
System.out.println(str);
}
Run Code Online (Sandbox Code Playgroud)
在regex中添加制表也很有用.
给定一个字符串 str:
str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
Run Code Online (Sandbox Code Playgroud)