深圳网站建设公司佳速互联,海淀做网站哪家公司好,在网站建设中要注意的问题,网站建设公司一年赚多少简介
在我们的代码中经常需要对字符串判空#xff0c;截取字符串、转换大小写、分隔字符串、比较字符串、去掉多余空格、拼接字符串、使用正则表达式等等。如果只用 String 类提供的那些方法#xff0c;我们需要手写大量的额外代码#xff0c;不然容易出现各种异常。现在有…简介
在我们的代码中经常需要对字符串判空截取字符串、转换大小写、分隔字符串、比较字符串、去掉多余空格、拼接字符串、使用正则表达式等等。如果只用 String 类提供的那些方法我们需要手写大量的额外代码不然容易出现各种异常。现在有个好消息是org.apache.commons.lang3包下的StringUtils工具类给我们提供了非常丰富的选择。
Maven依赖
dependencygroupIdorg.apache.commons/groupIdartifactIdcommons-lang3/artifactIdversion3.12.0/version
/dependency方法列表和描述
IsEmpty/IsBlank - 检查字符串是否包含文本Trim/Strip - 移除字符串的前导和尾随空白Equals/Compare - 以空安全的方式比较两个字符串startsWith - 以空安全的方式检查字符串是否以指定前缀开头endsWith - 以空安全的方式检查字符串是否以指定后缀结尾IndexOf/LastIndexOf/Contains - 空安全的索引检查IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - 在一组字符串中查找任意字符串的索引ContainsOnly/ContainsNone/ContainsAny - 检查字符串是否只包含/不包含/包含任意一组字符Substring/Left/Right/Mid - 空安全的子字符串提取SubstringBefore/SubstringAfter/SubstringBetween - 相对于其他字符串的子字符串提取Split/Join - 将字符串拆分为子字符串数组反之亦然Remove/Delete - 移除字符串的部分内容Replace/Overlay - 在字符串中搜索并用另一个字符串替换Chomp/Chop - 移除字符串的最后一部分AppendIfMissing - 如果不存在将后缀追加到字符串的末尾PrependIfMissing - 如果不存在将前缀添加到字符串的开头LeftPad/RightPad/Center/Repeat - 填充字符串UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - 更改字符串的大小写CountMatches - 计算一个字符串在另一个字符串中出现的次数IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - 检查字符串中的字符DefaultString - 防止空输入字符串Rotate - 旋转循环移位字符串Reverse/ReverseDelimited - 反转字符串Abbreviate - 使用省略号或另一个给定的字符串缩写字符串Difference - 比较字符串并报告它们之间的差异LevenshteinDistance - 将一个字符串更改为另一个所需的更改次数
empyt和blank都是判空有什么区别 isEmpty 返回falseisBlank返回true
一些常用的字符串常量
使用DEMO
1 判断字符串是否为空或者空白
import org.apache.commons.lang3.StringUtils;public class StringUtilsDemo {public static void main(String[] args) {String str1 Hello, World!;String str2 ;// 判断字符串是否为空或者空白System.out.println(Is str1 empty or blank? StringUtils.isBlank(str1));System.out.println(Is str2 empty or blank? StringUtils.isBlank(str2));}
}2 连接多个字符串
import org.apache.commons.lang3.StringUtils;public class StringUtilsDemo {public static void main(String[] args) {String[] words {Hello, World, Java};// 连接多个字符串String result StringUtils.join(words, );System.out.println(Result: result);}
}截取字符串的前几个字符
import org.apache.commons.lang3.StringUtils;public class StringUtilsDemo {public static void main(String[] args) {String original Apache StringUtils Demo;// 截取字符串的前几个字符String substring StringUtils.left(original, 10);System.out.println(Substring: substring);}
}4 移除字符串中的空格
import org.apache.commons.lang3.StringUtils;public class StringUtilsDemo {public static void main(String[] args) {String stringWithSpaces Remove Spaces ;// 移除字符串中的空格String result StringUtils.deleteWhitespace(stringWithSpaces);System.out.println(Result: result);}
}