package com.ynet.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Arya on 2017/11/3 0003.
*/
public class StringUtil {
//去除所有空格
public static String replaceAllBlank(String str) {
String s = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
/*\n 回车(\u000a)
\t 水平制表符(\u0009)
\s 空格(\u0008)
\r 换行(\u000d)*/
Matcher m = p.matcher(str);
s = m.replaceAll("");
}
return s;
}
//去除所有空格,留下一个
public static String replaceBlankLeaveOne(String str) {
String s = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s{2,}|\t|\r|\n");
Matcher m = p.matcher(str);
s = m.replaceAll(" ");
}
return s;
}
public static void main(String[] args) {
System.out.println(StringUtil.replaceAllBlank("just do it!"));
System.out.println(StringUtil.replaceBlankLeaveOne("just do it!"));
}
}
运行效果: