[英]Optimal way to replace \n \r and \t from a given String
Is there a better way to do this in Java: 在Java中是否有更好的方法可以做到这一点:
public static String clearLog(String message) {
return message.replace('\n', ' ').replace('\r', ' ').replace( '\t' , ' ');
}
I know this creates 3 String object and I want to avoid it. 我知道这会创建3 String对象,我想避免它。
You can use String::replaceAll
like this : 您可以像这样使用
String::replaceAll
:
message.replaceAll("[\n\r\t]", " ");
because replaceAll
uses regex, so you can create a class which holds these three characters [\\n\\r\\t]
replacing \\n
or \\r
or \\t
with a space. 因为
replaceAll
使用正则表达式,所以您可以创建一个包含这三个字符[\\n\\r\\t]
的类,并用空格替换\\n
或\\r
或\\t
。
You can do it without regex using a char[]
: 您可以使用
char[]
而不使用正则表达式:
char[] cs = message.toCharArray();
for (int a = 0; a < cs.length; ++a) {
switch (cs[a]) {
case '\n': case '\r': case '\t':
cs[a] = ' ';
break;
}
}
return new String(cs);
This will likely be a lot faster than the regex approach because it's very simple code to execute: it doesn't involve the whole regex engine; 这可能比regex方法快很多,因为它是非常简单的代码执行:它不涉及整个regex引擎。 but it's more verbose, less readable and less flexible.
但是它比较冗长,可读性和灵活性较差。
Sure, use a Guava CharMatcher
. 当然,请使用Guava
CharMatcher
。
String cleaned = CharMatcher.anyOf("\t\n\r").trimAndCollapseFrom(yourString, ' ');
CharMatcher is heavily optimized and will limit object creation. CharMatcher经过了严格的优化,将限制对象的创建。 If you save the CharMatcher to a constant (you can, it's immutable), then this will only generate one interim Object, a
StringBuilder
. 如果将CharMatcher保存为一个常量(可以,它是不可变的),那么它将仅生成一个临时对象
StringBuilder
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.