我使用 trim()
方法来修剪某些字符串字段中的前导和尾随空格。
siteRequest.getName().trim();
但是,当字符串字段为空时,它会按预期抛出异常。我可以在修剪之前检查值,如下所示:
siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();
但是,如果可能的话,我更喜欢一种更清洁的方法,以便有几个人已经遇到过这个问题。有更聪明的方法的建议吗?
最佳答案
我喜欢@Sebastiaan van den Broek 的想法,但不希望使用该库,因此查找它的implementation :
// Trim
//-----------------------------------------------------------------------
/**
* <p>Removes control characters (char <= 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 <= 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();
}
在我看来,没有更好的方法来实现它。使用 Optionals 不是一种选择。因此,确认了问题中原来的解决思路。
关于Java修剪(): Cleanest way to check null string before trimming?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72520878/