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


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

    编写工具类 StringUtils

    1. 编写工具类

      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+$", "");
              }
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
    2. 测试工具

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

      @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());
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

      测试结果如下:

          李    昊    哲    
      19
      李    昊    哲    
      15
      
      • 1
      • 2
      • 3
      • 4

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

      @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());
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

      测试结果如下:

      	    李    昊    哲    
      19
          李    昊    哲
      15
      
      • 1
      • 2
      • 3
      • 4
  • 相关阅读:
    多线程基础原理篇
    antv x6 沿边图标循环动画实现
    窄带FxLMS算法
    wangEditor富文本编辑器的调用开发实录(v5版本、多个编辑器、php后端上传视频阿里云OSS、编辑HTML回显)
    JavaScript同步与异步
    Shell 运算符及语法结构
    算法补天系列之中级提高班1
    Vue3学习记录
    Python实现邮件发送时如何设置服务器参数?
    7.js对象
  • 原文地址:https://blog.csdn.net/qq_24330181/article/details/133885139