java去除字符串中的空格、回车、换行符、制表符
java去除字符串中的空格、回车、换行符、制表符的三种方法。
方法一:
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile("\s*| | | ");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
public static void main(String[] args) {
System.out.println(StringUtils.replaceBlank("just do it!"));
}
注: 回车(u000a)
水平制表符(u0009)
s 空格(u0008)
换行(u000d)*/
方法二:
str.replaceAll( "\s", "" ); 一句话搞定
方法三:
public static String trim(String str) {
if (str == null) {
return str;
}
str = str.trim();
for (int i = 0; i < str.length(); i++) {
int tmp = str.charAt(i);
if (tmp == 9 || tmp == 13 || tmp == 10 || tmp == 32 || tmp == 12288) {
continue;
} else {
str = str.substring(i);
break;
}
}
for (int i = str.length() - 1; i >= 0; i--) {
int tmp = str.charAt(i);
if (tmp == 9 || tmp == 13 || tmp == 10 || tmp == 32 || tmp == 12288) {
continue;
} else {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
java去除字符串中的空格、回车、换行符、制表符的三种方法。 方法一: public static String replaceBlank(String str) { String dest = ""; if (str!=null) { Pattern p = Pattern.compile("\s*| | | "); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } public static void main(String[] args) { System.out.println(StringUtils.replaceBlank("just do it!")); } 注: 回车(u000a) 水平制表符(u0009) s 空格(u0008) 换行(u000d)*/ 方法二: str.replaceAll( "\s", "" ); 一句话搞定 方法三: public static String trim(String str) { if (str == null) { return str; } str = str.trim(); for (int i = 0; i < str.length(); i++) { int tmp = str.charAt(i); if (tmp == 9 || tmp == 13 || tmp == 10 || tmp == 32 || tmp == 12288) { continue; } else { str = str.substring(i); break; } } for (int i = str.length() - 1; i >= 0; i--) { int tmp = str.charAt(i); if (tmp == 9 || tmp == 13 || tmp == 10 || tmp == 32 || tmp == 12288) { continue; } else { str = str.substring(0, i + 1); break; } } return str; }