我使用trim()
方法来修剪一些字符串字段中的前导和尾随空格.
siteRequest.getName().trim();
然而,当字符串字段为null时,它会按预期引发异常.我可以在修剪前判断值,如下所示:
siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();
然而,如果可能的话,我更喜欢一种更干净的方式,这样一些人就已经面临这个问题了.有什么更明智的建议吗?
我使用trim()
方法来修剪一些字符串字段中的前导和尾随空格.
siteRequest.getName().trim();
然而,当字符串字段为null时,它会按预期引发异常.我可以在修剪前判断值,如下所示:
siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();
然而,如果可能的话,我更喜欢一种更干净的方式,这样一些人就已经面临这个问题了.有什么更明智的建议吗?
我喜欢@Sebastiaan van den Broek的 idea ,但不想使用图书馆,因此请查阅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不是一个选项.因此,问题的原始解决思路得到了确认.