zoukankan      html  css  js  c++  java
  • Java中去除字符串中空格的方法

    昨天写了一个关于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()不同的时,只替换第一次出现的字符串

  • 相关阅读:
    高可用的MongoDB集群-实战篇
    【转载】特征选择常用算法综述
    【转载】Pytorch tutorial 之Datar Loading and Processing
    论文笔记系列-Well Begun Is Half Done:Generating High-Quality Seeds for Automatic Image Dataset Construction from Web
    重新定义Pytorch中的TensorDataset,可实现transforms
    【转载】机器学习之特征工程
    Pytorch里的CrossEntropyLoss详解
    Python日志模块logging用法
    【转载】如何进行数据变换
    【转载】使用sklearn优雅地进行数据挖掘
  • 原文地址:https://www.cnblogs.com/telwanggs/p/11427590.html
Copyright © 2011-2022 走看看