java中如何去除字符串中的空格\t、回車\n、換行符\r、製表符\t?

public class StringUtils {
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    
    public static void main(String[] args) {
        System.out.println(StringUtils.replaceBlank("just do it!"));
    }
    /*-----------------------------------
 
    笨方法:String s = "你要去除的字符串";
 
            1.去除空格:s = s.replace('\\s','');
 
            2.去除回車:s = s.replace('\n','');
    這樣也可以把空格和回車去掉,其他也可以照這樣做。
 
    注:\n 回車(\u000a)
    \t 水平製表符(\u0009)
    \s 空格(\u0008)
    \r 換行(\u000d)*/
}

如果使用了spring,可以用其中的一個方法StringUtils.trimAllWhitespace,可以去掉所有空白符,和上述功能類似。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章