java去掉String里面的空格、換行符等


 1 package com.ynet.utils;
 2 
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 /**
 7  * Created by Arya on 2017/11/3 0003.
 8  */
 9 public class StringUtil {
10     //去除所有空格
11     public static String replaceAllBlank(String str) {
12         String s = "";
13         if (str!=null) {
14             Pattern p = Pattern.compile("\\s*|\t|\r|\n");
15             /*\n 回車(\u000a)
16             \t 水平制表符(\u0009)
17             \s 空格(\u0008)
18             \r 換行(\u000d)*/
19             Matcher m = p.matcher(str);
20             s = m.replaceAll("");
21         }
22         return s;
23     }
24     //去除所有空格,留下一個
25     public static String replaceBlankLeaveOne(String str) {
26         String s = "";
27         if (str!=null) {
28             Pattern p = Pattern.compile("\\s{2,}|\t|\r|\n");
29             Matcher m = p.matcher(str);
30             s = m.replaceAll(" ");
31         }
32         return s;
33     }
34 
35     public static void main(String[] args) {
36         System.out.println(StringUtil.replaceAllBlank("just    do     it!"));
37         System.out.println(StringUtil.replaceBlankLeaveOne("just    do     it!"));
38     }
39 
40 }

運行效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM