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
相关推荐
u***j3241 小时前
后端服务限流实现,Redis+Lua脚本
java·redis·lua
CoderYanger1 小时前
A.每日一题——2536. 子矩阵元素加 1
java·线性代数·算法·leetcode·矩阵
不可描述的两脚兽1 小时前
Redis 快记
java·数据库·redis
sanggou1 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友1 小时前
C++与Qt图形开发
开发语言·c++·算法
yue0082 小时前
C# 更改窗体样式
开发语言·c#
普通网友2 小时前
C++中的适配器模式
开发语言·c++·算法
风闲12172 小时前
Qt源码编译记录
开发语言·qt
Felix_XXXXL2 小时前
mysql查看binlog日志
java·后端
leonardee2 小时前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端