java去掉String里面的空格、换行符等 | 您所在的位置:网站首页 › java字符串去掉空格 › java去掉String里面的空格、换行符等 |
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 }
运行效果:
posted on 2017-11-03 19:09 秀川 阅读(15170) 评论(0) 编辑 收藏 举报 |
CopyRight 2018-2019 实验室设备网 版权所有 |