java.lang.String.trim()函数的使用

本文详细介绍了Java中String类的trim()方法的功能和使用方法,通过示例代码展示了如何去除字符串两端的空白字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String java.lang.String.trim()

先来个例子:

public static void main(String arg[]){
    String a = "  Hello World!  ";
    String b = "Hello World!";
    System.out.println("a--" + a + "--");
    System.out.println("b--" + b + "--");
    System.out.println(a.equals(b));
    a = a.trim();//去除首尾字符
    System.out.println("a--" + a + "--");
    System.out.println(a.equals(b));
}

运行结果:

运行结果

简单解释:

java.lang.String.trim() 方法返回一个字符串副本,并忽略(去除)开头和结尾的空格.

官方解释

Returns a string whose value is this string, with any leading and trailing whitespace removed.

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than ‘\u0020’ (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than ‘\u0020’ in the string, then a String object representing an empty string is returned.

Otherwise, let k be the index of the first character in the string whose code is greater than ‘\u0020’ , and let m be the index of the last character in the string whose code is greater than ‘\u0020’ . A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m -that is, the result of this.substring(k, m + 1) .

This method may be used to trim whitespace (as defined above) from the beginning and end of a string. Returns: A string whose value is this string, with any leading and trailing white space removed, or this string if it has no leading or trailing white space.

### 处理 Java 中字符串为空导致的 `NullPointerException` 为了避免因字符串为空而导致的`NullPointerException`,可以采取多种策略来安全地检查和处理字符串。以下是几种常见且有效的方法: #### 方法一:双重条件检查 通过先验证字符串是否为`null`再调用其成员函数的方式能够有效地防止异常的发生。 ```java if (str != null && !str.isEmpty()) { // 执行逻辑... } ``` 这种方法简单直观,适用于大多数场景[^2]。 #### 方法二:使用工具类库 Apache Commons Lang 提供了一个非常实用的静态方法——`StringUtils.isNotEmpty()`或`StringUtils.isBlank()`,这些方法内部已经做了充分优化并能很好地应对各种边界情况。 ```java import org.apache.commons.lang3.StringUtils; // 判断字符串既不是null也不是空白(仅含空格也被视为blank) if (StringUtils.isNotBlank(str)) { // 执行逻辑... } ``` 此法不仅简洁而且性能良好,推荐在项目中有引入相应依赖的情况下优先考虑[^1]。 #### 方法三:默认值替换 当遇到可能为`null`的字符串变量时,可以通过`String.valueOf(Object obj)`或者`Objects.toString(T o, String nullDefault)`将其转换成非`null`形式,默认返回指定的内容而非抛出异常。 ```java // 将潜在的null转为"" String safeStr = Objects.toString(originalStr, ""); ``` 这种方式可以在不影响原有业务流程的前提下优雅地规避风险[^4]。 #### 方法四:Optional API(Java 8及以上) 利用`Optional.ofNullable()`配合流式API实现更现代化的写作风格,同时也能达到同样的效果。 ```java Optional<String> optStr = Optional.ofNullable(str); optStr.filter(s -> !s.trim().isEmpty()) .orElseThrow(() -> new IllegalArgumentException("Invalid input")); ``` 这有助于提升代码可读性和表达力的同时增强了安全性。 以上四种方案各有优劣,在实际开发过程中可以根据具体需求和个人偏好灵活选用最合适的办法来预防由字符串引发的`NullPointerException`问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值