首页 > 编程 > Java > 正文

Java去除字符串中空格的方法详解

2019-11-26 08:39:50
字体:
来源:转载
供稿:网友

昨天写了一个关于Excel文件处理的脚本,在字符串匹配功能上总是出现多余不正确的匹配,debug调试之后,发现一个坑。

------->代码中字符串使用了replaceAll()方法,去除了所有空格(其中包括:首尾空格、中间空格)

遂整理下java关于字符串去除空格的方法。

1、方法分类

  • str.trim(); //去掉首尾空格
  • str.replace(" ",""); //去除所有空格,包括首尾、中间
  • str.replaceAll(" ", ""); //去掉所有空格,包括首尾、中间
  • str.replaceAll(" +",""); //去掉所有空格,包括首尾、中间
  • str.replaceAll("//s*", ""); //可以替换大部分空白字符, 不限于空格 ;

//s* 可以匹配空格、制表符、换页符等空白字符的其中任意一个。

2、代码示例

package test;public class Test {    /**   * description:字符串去除空格的方法   */  public static void main(String[] args) {    String str = " hi world ~ ";        //方法1:str.trim()    System.out.println("1--->"+str.trim());    //方法2:str.repalce(" ","")    System.out.println("2--->"+str.replace(" ", ""));    //方法3:str.repalceAll(" ","")    System.out.println("3--->"+str.replaceAll(" ", ""));    //方法4:str.repalceAll(" +","")    System.out.println("4--->"+str.replaceAll(" +", ""));    //方法5:str.repalceAll("//s*","")    System.out.println("4--->"+str.replaceAll("//s*", ""));  }}

3、输出结果

4、replace和replaceAll是JAVA中常用的替换字符的方法,它们的区别是:

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

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

相同点:都是全部替换,即把源字符串中的某一字符或字符串全部换成指定的字符或字符串,如果只想替换第一次出现的,可以使用

replaceFirst(),这个方法也是基于规则表达式的替换,但与replaceAll()不同的时,只替换第一次出现的字符串

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表