java去除空格、标点符号的方法实例

2023-05-17,,

代码如下:

public class TempTest {
 public static void main(String[] args) {
  //string去除空格
  String str=" hello world ";
  System.out.println(str);
 
  String str1=str.trim();//去除首尾空格
  System.out.println(str1);
 
  String str2=str.replace(" ","");//去掉所有空格,包括首尾,中间
  System.out.println(str2);
 
  String str3=str.replaceAll(" +","");//去掉所有空格,包括首尾,中间
  System.out.println(str3);
 
  String str4=str.replaceAll("\\s*",""); //可以替换大部分空白字符, 不限于空格 . 说明:\s 可以匹配空格、制表符、换页符等空白字符的其中任意一个
  System.out.println(str4);
 
  //string去除标点符号
  //正则表达式去除标点
  String stri="ss&*(,.~1如果@&(^-自己!!知道`什`么#是$苦%……Z,&那*()么一-=定——+告诉::;\"'/?.,><[]{}\\||别人什么是甜。";
  System.out.println(stri);
 
  String stri1=stri.replaceAll("\\p{Punct}","");//不能完全清除标点
  System.out.println(stri1);
 
  String stri2=stri.replaceAll("\\pP","");//完全清除标点
  System.out.println(stri2);
 
  String stri3=stri.replaceAll("\\p{P}","");//同上,一样的功能
  System.out.println(stri3);
 
  String stri4=stri.replaceAll("[\\pP\\p{Punct}]","");//清除所有符号,只留下字母 数字 汉字 共3类.
  System.out.println(stri4);
 }
}

运行结果:

  hello   world 
hello   world
helloworld
helloworld
helloworld
ss&*(,.~1如果@&(^-自己!!知道`什`么#是$苦%……Z,&那*()么一-=定——+告诉::;"'/?.,><[]{}\||别人什么是甜。
ss1如果自己知道什么是苦……Z,那么一定——告诉别人什么是甜。
ss~1如果^自己知道`什`么是$苦Z那么一=定+告诉><||别人什么是甜
ss~1如果^自己知道`什`么是$苦Z那么一=定+告诉><||别人什么是甜
ss1如果自己知道什么是苦Z那么一定告诉别人什么是甜

关于replace 和replaceAll:

replace(char oldChar,char newChar)

replace(CharSequence target,CharSequence replacement)

replaceAll(String regex,String replacement)

1)replace的参数是char和CharSequence,即可以支持字符的替换,也支持字符串的替换(CharSequence即字符串序列的意思,说白了也就是字符串);

2)replaceAll的参数是regex,即基于规则表达式的替换,比如,可以通过replaceAll("\\d", "*")把一个字符串所有的数字字符都换成星号;

相同点是都是全部替换,即把源字符串中的某一字符或字符串全部换成指定的字符或字符串,如果只想替换第一次出现的,可以使用 replaceFirst(),这个方法也是基于规则表达式的替换,但与replaceAll()不同的是,只替换第一次出现的字符串;

另外,如果replaceAll()和replaceFirst()所用的参数据不是基于规则表达式的,则与replace()替换字符串的效果是一样的,即这两者也支持字符串的操作;

还有一点注意:执行了替换操作后,源字符串的内容是没有发生改变的.

总结

到此这篇关于java去除空格、标点符号的文章就介绍到这了,更多相关java去除空格、标点符号内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

《java去除空格、标点符号的方法实例.doc》

下载本文的Word格式文档,以方便收藏与打印。