1. 程式人生 > >java去掉String裏面的空格、換行符等

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

leave package != null mat import stat img []

 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 }

運行效果:

技術分享

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