(代码)java去除字符串中的空格、回车、换行符、制表符

\n

回车(\u000a)

\t

水平制表符(\u0009)

\s

空格(\u0008)

\r

换行(\u000d)

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
//方法一:使用正则表达式替换
public static String replaceCharReg(String value) {
String result = "";
if (value!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(value);
result = m.replaceAll("");
}
return result;
}
//方法二:使用replace函数替换
public static String replaceChar(String value) {
String result = "";
if (value!=null) {
//1.去掉空格:
value = value.replace("\\s","");
//2.去掉回车:
value = value.replace("\n","");
//3.去掉换行:
value = value.replace("\r","");
//4.水平制表符:
value = value.replace("\t","");
result=value;
}
return result;
}
public static void main(String[] args) {
System.out.println(replaceCharReg("360 sdn com"));
System.out.println(replaceChar("360 sdn com"));
}
}