简体   繁体   中英

Optimal way to replace \n \r and \t from a given String

Is there a better way to do this in 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.

You can use String::replaceAll like this :

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.

You can do it without regex using a 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; but it's more verbose, less readable and less flexible.

Sure, use a Guava CharMatcher .

String cleaned = CharMatcher.anyOf("\t\n\r").trimAndCollapseFrom(yourString, ' ');

CharMatcher is heavily optimized and will limit object creation. If you save the CharMatcher to a constant (you can, it's immutable), then this will only generate one interim Object, a StringBuilder .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM