加入了trim()方法,没有去掉多余空格

yanhongwen / 2024-07-09 / 原文

原因:

        直接使用String自带的 trim 方法,返回给原String类型变量(如修改前代码)。原始的 customerMessage 字符串对象的值是不会发生变化的,因为String 类型都是不可变的,只能通过创建新的字符串对象来表达修改后的值。

 

修改前代码

import cn.hutool.core.util.StrUtil;

public class Main {
    public static void main(String[] args) {
        String customerMessage = "  Hello, World!  ";
        customerMessage = customerMessage.trim(customerMessage);
        
        System.out.println(customerMessage); // 输出: "  Hello, World!  "
    }
}

 

解决办法

        将去掉空格的值,赋值到一个新的String类型的变量中。或者使用hutool工具包的StrUtil,trim(),这个方法并没有修改原始的 customerMessage 字符串对象,而是创建了一个新的修剪后的字符串对象,并将其赋值给 customerMessage 变量。

 

修改后代码

import cn.hutool.core.util.StrUtil;

public class Main {
    public static void main(String[] args) {
        String customerMessage = "  Hello, World!  ";
        customerMessage = StrUtil.trim(customerMessage);
        
        System.out.println(customerMessage); // 输出: "Hello, World!"
    }
}