Java trim():在修剪之前检查空字符串的最干净方法?

5 java string trim string-formatting spring-boot

我使用trim()方法来修剪某些字符串字段中的前导和尾随空格。

siteRequest.getName().trim();
Run Code Online (Sandbox Code Playgroud)

但是,当字符串字段为空时,它会按预期抛出异常。我可以在修剪之前检查这些值,如下所示:

siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();
Run Code Online (Sandbox Code Playgroud)

然而,如果可能的话,我更喜欢一种更干净的方式,这样已经有几个人遇到了这个问题。有什么更明智的方法建议吗?

Fra*_*nck 6

我喜欢 @Sebastiaan van den Broek 的想法,但不想使用该库,因此查找其实现

// Trim
//-----------------------------------------------------------------------
/**
 * <p>Removes control characters (char &lt;= 32) from both
 * ends of this String, handling {@code null} by returning
 * {@code null}.</p>
 *
 * <p>The String is trimmed using {@link String#trim()}.
 * Trim removes start and end characters &lt;= 32.
 * To strip whitespace use {@link #strip(String)}.</p>
 *
 * <p>To trim your choice of characters, use the
 * {@link #strip(String, String)} methods.</p>
 *
 * <pre>
 * StringUtils.trim(null)          = null
 * StringUtils.trim("")            = ""
 * StringUtils.trim("     ")       = ""
 * StringUtils.trim("abc")         = "abc"
 * StringUtils.trim("    abc    ") = "abc"
 * </pre>
 *
 * @param str  the String to be trimmed, may be null
 * @return the trimmed string, {@code null} if null String input
 */
public static String trim(final String str) {
    return str == null ? null : str.trim();
}
Run Code Online (Sandbox Code Playgroud)

从我的角度来看,没有更好的方法来实现它。使用Optionals 不是一个选项。因此,问题中原来的解题思路得到了证实。