Java 代码 实现 字符串去掉左边空格 字符串去掉右边空格

Java 代码 实现 字符串去掉左边空格 字符串去掉右边空格

编写工具类 StringUtils

  1. 编写工具类

    java 复制代码
    package com.lihaozhe.util.string;
    
    /**
     * 字符串工具类
     *
     * @author 李昊哲
     * @version 1.0
     * @create 2023/10/17
     */
    public class StringUtils {
        /**
         * 去除字符串左边的的空格
         *
         * @param string 原始字符串
         * @return 去除左边空格后的字符串
         */
        public static String ltrim(String string) {
            if (string == null) {
                throw new NullPointerException();
            } else {
                return string.replaceAll("^\\s+", "");
            }
        }
    
        /**
         * 去除字符串右边的的空格
         *
         * @param string 原始字符串
         * @return 去除右边空格后的字符串
         */
        public static String rtrim(String string) {
            if (string == null) {
                throw new NullPointerException();
            } else {
                return string.replaceAll("\\s+$", "");
            }
        }
    }
  2. 测试工具类

    2.1 测试去掉字符串左边空格

    java 复制代码
    @Test
    public void test07() {
        String name = "    李    昊    哲    ";
        System.out.println(name);
        System.out.println(name.length());
        String ltrim = StringUtils.ltrim(name);
        System.out.println(ltrim);
        System.out.println(ltrim.length());
    }

    测试结果如下:

    java 复制代码
        李    昊    哲    
    19
    李    昊    哲    
    15

    2.2 测试去掉字符串左边空格

    java 复制代码
    @Test
    public void test08() {
        String name = "    李    昊    哲    ";
        System.out.println(name);
        System.out.println(name.length());
        String rtrim = StringUtils.rtrim(name);
        System.out.println(rtrim);
        System.out.println(rtrim.length());
    }

    测试结果如下:

    java 复制代码
    	    李    昊    哲    
    19
        李    昊    哲
    15
相关推荐
先知后行。21 小时前
C/C++八股文
java·开发语言
Yeats_Liao21 小时前
时序数据库系列(五):InfluxDB聚合函数与数据分析
java·后端·数据分析·时序数据库
程序员buddha1 天前
C语言数组详解
c语言·开发语言·算法
寻找华年的锦瑟1 天前
Qt-视频播放器
开发语言·qt
又是忙碌的一天1 天前
Java IO流
java·开发语言
程序员buddha1 天前
springboot-mvc项目示例代码
java·spring boot·mvc
fish_study_csdn1 天前
Python内存管理机制
开发语言·python·c python
不懂英语的程序猿1 天前
【Java 工具类】Java通过 TCP/IP 调用斑马打印机(完整实现)
java
ghie90901 天前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
你的人类朋友1 天前
✍️记录自己的git分支管理实践
前端·git·后端