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

发布时间:2020-10-24 20:11:28 作者:iCoding91
来源:脚本之家 阅读:274

代码如下:

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去除空格、标点符号内容请搜索亿速云以前的文章或继续浏览下面的相关文章希望大家以后多多支持亿速云!

推荐阅读:
  1. python中去除标点符号的方法
  2. Java去除字符串中空格的方法详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 去除 空格

上一篇:jquery实现的放大镜效果示例

下一篇:iOS7 弹出UIActionSheet,UIImagePickerViewController的navigationbar代理,搜索未用到的图片

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》