需要的jar包:commons-lang3
public class StringTemple { private static final Log LOG = LogFactory.getLog(StringTemple.class); private static String STR = "this is a test string 123"; public static void main(String[] args) { if (StringUtils.isNotEmpty(STR)) { LOG.info("STR 不为null,且长度>0"); } if (StringUtils.isBlank(" ")) { LOG.info("如果空格为空的话使用isBlank判断"); } String trimToNull = StringUtils.trimToNull(" "); LOG.info(trimToNull); String trimToEmpty = StringUtils.trimToEmpty(" "); LOG.info(trimToEmpty); //如果字符串为 ""," ",null,则给一个默认的字符串“blank” String blank = StringUtils.defaultIfBlank(" ", "blank"); LOG.info(blank); //如果字符串为"",null,则给一个默认的字符串“empty” String empty = StringUtils.defaultIfEmpty("", "empty"); LOG.info(empty); //把数组的每个值用特定的符号连起来 String[] str = {"a", "b", "c"}; String join = StringUtils.join(str, ","); LOG.info(join); //字符串首字母大写 String capitalize = StringUtils.capitalize(STR); LOG.info(STR + "首字母大写 : " + capitalize); //字符串首字母小写 String uncapitalize = StringUtils.uncapitalize(capitalize); LOG.info(capitalize + "首字母小写 : " + uncapitalize); boolean isContainIgnoreCase = StringUtils.containsIgnoreCase(STR, "Is"); LOG.info(isContainIgnoreCase); //字符串替换 String replace = StringUtils.replace(STR, "is", "si"); LOG.info(STR + "把is 替换成 si : " + replace); //判断字符串是否是纯数字 String numStr = "123"; boolean isNumeric = StringUtils.isNumeric(numStr); LOG.info(numStr + " is numeric ? : " + isNumeric); //判断字符串是为是字母或数字 String alphanStr = "abc123"; boolean isAlphanumeric = StringUtils.isAlphanumeric(alphanStr); LOG.info(alphanStr + " is alphanumeric ? : " + isAlphanumeric); String defaultString = StringUtils.defaultString(numStr); LOG.info(defaultString); //字符串重复n次 String repeat = StringUtils.repeat(STR, " ", 3); LOG.info(STR + "重复3次后结果为:" + repeat); String reverse = StringUtils.reverse(STR); LOG.info(STR + "反转之后的结果是: " + reverse); //长度不够时,向左用*补位 String leftPad = StringUtils.leftPad("this is", 10, "*"); LOG.info(leftPad); //长度不够时,向右用*补位 String rightPad = StringUtils.rightPad("this is", 10, "*"); LOG.info(rightPad); //判断字符串是否包含空格 boolean containWhitespace = StringUtils.containsWhitespace(STR); LOG.info(STR + "包含空格? " + containWhitespace); //删除所有的空格 String delWithspace = StringUtils.deleteWhitespace("this is "); LOG.info(STR + "去掉空格之后结果为 : " + delWithspace); String subAfter = StringUtils.substringAfter(STR, "st"); LOG.info(STR + "after "st" substringAfter is : " + subAfter); String subBefore = StringUtils.substringBefore(STR, "is"); LOG.info(STR + "after "is" substringBefore is : " + subBefore); String subBetween = StringUtils.substringBetween(STR, "is", "st"); LOG.info(STR + "after substringBetween "is" and "st" is : " + subBetween); } }