亚马逊的StringUtils类
StringUtils
public final class StringUtils {
private static final String EMPTY = "";
private StringUtils(){
}
/**
* <p>Checks if a CharSequence is empty("") or null.</p>
* StringUtils.isEmpty(null) = true;
* StringUtils.isEmpty("") = true;
* StringUtils.isEmpty(" ") = false;
* StringUtils.isEmpty("bob") = false;
* StringUtils.isEmpty(" bob ") = false;
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is empty(""), null or whitespace only.</p>
* StringUtils.isEmpty(null) = true;
* StringUtils.isEmpty("") = true;
* StringUtils.isEmpty(" ") = true;
* StringUtils.isEmpty("bob") = false;
* StringUtils.isEmpty(" bob ") = false;
*/
public static boolean isBlank(final CharSequence cs){
if(cs == null || cs.length() == 0) {
return true;
}
for (int i = 0; i < cs.length(); i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty(""), not null and not whitespace only.</p>
* StringUtils.isEmpty(null) = false;
* StringUtils.isEmpty("") = false;
* StringUtils.isEmpty(" ") = false;
* StringUtils.isEmpty("bob") = true;
* StringUtils.isEmpty(" bob ") = true;
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
/**
* <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.</p>
* StringUtils.isEmpty(null) = null;
* StringUtils.isEmpty("") = "";
* StringUtils.isEmpty(" ") = "";
* StringUtils.isEmpty("bob") = "bob";
* StringUtils.isEmpty(" bob ") = "bob";
*/
public static String trim(final String str) {
return str == null ? null : str.trim();
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning {@code null} if the String is
* empty ("") after the trim of if it is {@code null}</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.</p>
*
* StringUtils.isEmpty(null) = null;
* StringUtils.isEmpty("") = null;
* StringUtils.isEmpty(" ") = null;
* StringUtils.isEmpty("bob") = "bob";
* StringUtils.isEmpty(" bob ") = "bob";
*/
public static String trimToNull(final String str) {
String ts = trim(str);
return isEmpty(ts) ? null : ts;
}
/**
* <p>Removes control characters (char <= 32) from both
* ends of this String returning an empty String ("") if the String
* is empty ("") after the trim of if it is {@code null}</p>
*
* <p>The String is trimmed using {@link String#trim()}.
* Trim removes start and end characters <= 32.</p>
*
* StringUtils.isEmpty(null) = "";
* StringUtils.isEmpty("") = "";
* StringUtils.isEmpty(" ") = "";
* StringUtils.isEmpty("bob") = "bob";
* StringUtils.isEmpty(" bob ") = "bob";
*/
public static String trimToEmpty(final String str) {
return str == null ? EMPTY : str.trim();
}
}