public class StrUtils {
public static void main(String[] args) {
String trim = StringUtils.trim(" 移除两边空字符串 ");
System.out.println("---移除两边空字符串--"+trim);
//删除字符串中的梭有空格
StringUtils.deleteWhitespace(" ab c ");//---"abc"
String removeStart = StringUtils.removeStart("www.foxwho.com","www.foxwho");
System.out.println("---removeStart---"+removeStart);
StringUtils.strip("删除指定字符串");
String rightPad = StringUtils.rightPad("23",5,"0");
System.out.println("---右补齐---"+rightPad);
String leftPad = StringUtils.leftPad("23",5,"0");
System.out.println("---左补齐---"+leftPad);
String center = StringUtils.center("刘",2,"光");
System.out.println("---center--"+center);
//缩短到某长度,用...结尾.其实就是(substring(str, 0, max-3) + "...")
//public static String abbreviate(String str,int maxWidth)
StringUtils.abbreviate("abcdefg", 6);// ---"abc..."
//字符串结尾的后缀是否与你要结尾的后缀匹配,若不匹配则添加后缀
StringUtils.appendIfMissing("abc","xyz");//---"abcxyz"
StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz");//---"abcXYZ"
//首字母大小写转换
StringUtils.capitalize("cat");//---"Cat"
StringUtils.uncapitalize("Cat");//---"cat"
//字符串扩充至指定大小且居中(若扩充大小少于原字符大小则返回原字符,若扩充大小为 负数则为0计算 )
StringUtils.center("abcd", 2);//--- "abcd"
StringUtils.center("ab", -1);//--- "ab"
StringUtils.center("ab", 4);//---" ab "
StringUtils.center("a", 4, "yz");//---"yayz"
StringUtils.center("abc", 7, "");//---" abc "
//去除字符串中的"\n", "\r", or "\r\n"
StringUtils.chomp("abc\r\n");//---"abc"
//判断一字符串是否包含另一字符串
StringUtils.contains("abc", "z");//---false
StringUtils.containsIgnoreCase("abc", "A");//---true
//统计一字符串在另一字符串中出现次数
StringUtils.countMatches("abba", "a");//---2
//比较两字符串,返回不同之处。确切的说是返回第二个参数中与第一个参数所不同的字符串
StringUtils.difference("abcde", "abxyz");//---"xyz"
//检查字符串结尾后缀是否匹配
StringUtils.endsWith("abcdef", "def");//---true
StringUtils.endsWithIgnoreCase("ABCDEF", "def");//---true
StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//检查起始字符串是否匹配
StringUtils.startsWith("abcdef", "abc");//---true
StringUtils.startsWithIgnoreCase("ABCDEF", "abc");//---true
StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true
//判断两字符串是否相同
StringUtils.equals("abc", "abc");//---true
StringUtils.equalsIgnoreCase("abc", "ABC");//---true
//比较字符串数组内的所有元素的字符序列,起始一致则返回一致的字符串,若无则返回""
StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"});//---"ab"
//正向查找字符在字符串中第一次出现的位置
StringUtils.indexOf("aabaabaa", "b");//---2
StringUtils.indexOf("aabaabaa", "b", 3);//---5(从角标3后查找)
StringUtils.ordinalIndexOf("aabaabaa", "a", 3);//---1(查找第n次出现的位置)
//反向查找字符串第一次出现的位置
StringUtils.lastIndexOf("aabaabaa", "b");//---5
StringUtils.lastIndexOf("aabaabaa", "b", 4);//---2
StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2);//---1
//判断字符串大写、小写
StringUtils.isAllUpperCase("ABC");//---true
StringUtils.isAllLowerCase("abC");//---false
//判断是否为空(注:isBlank与isEmpty 区别)
StringUtils.isBlank(null);StringUtils.isBlank("");StringUtils.isBlank(" ");//---true
StringUtils.isNoneBlank(" ", "bar");//---false
StringUtils.isEmpty(null);StringUtils.isEmpty("");//---true
StringUtils.isEmpty(" ");//---false
StringUtils.isNoneEmpty(" ", "bar");//---true
//判断字符串数字
StringUtils.isNumeric("123");//---false
StringUtils.isNumeric("12 3");//---false (不识别运算符号、小数点、空格……)
StringUtils.isNumericSpace("12 3");//---true
//数组中加入分隔符号
//StringUtils.join([1, 2, 3], ‘;‘);//---"1;2;3"
//大小写转换
StringUtils.upperCase("aBc");//---"ABC"
StringUtils.lowerCase("aBc");//---"abc"
StringUtils.swapCase("The dog has a BONE");//---"tHE DOG HAS A bone"
//替换字符串内容……(replacePattern、replceOnce)
StringUtils.replace("aba", "a", "z");//---"zbz"
StringUtils.overlay("abcdef", "zz", 2, 4);//---"abzzef"(指定区域)
StringUtils.replaceEach("abcde", new String[]{"ab", "d"},
new String[]{"w", "t"});//---"wcte"(多组指定替换ab->w,d->t)
//重复字符
StringUtils.repeat("e", 3);//---"eee"
//反转字符串
StringUtils.reverse("bat");//---"tab"
//删除某字符
StringUtils.remove("queued", "u");//---"qeed"
//分割字符串
StringUtils.split("a..b.c", ".");//---["a", "b", "c"]
StringUtils.split("ab:cd:ef", ":", 2);//---["ab", "cd:ef"]
StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2);//---["ab", "cd-!-ef"]
StringUtils.splitByWholeSeparatorPreserveAllTokens("ab::cd:ef", ":");//-["ab"," ","cd","ef"]
//去除首尾空格,类似trim……(stripStart、stripEnd、stripAll、stripAccents)
StringUtils.strip(" ab c ");//---"ab c"
StringUtils.stripToNull(null);//---null
StringUtils.stripToEmpty(null);//---""
//截取字符串
StringUtils.substring("abcd", 2);//---"cd"
StringUtils.substring("abcdef", 2, 4);//---"cd"
//left、right从左(右)开始截取n位字符
StringUtils.left("abc", 2);//---"ab"
StringUtils.right("abc", 2);//---"bc"
//从第n位开始截取m位字符 n m
StringUtils.mid("abcdefg", 2, 4);//---"cdef"
StringUtils.substringBefore("abcba", "b");//---"a"
StringUtils.substringBeforeLast("abcba", "b");//---"abc"
StringUtils.substringAfter("abcba", "b");//---"cba"
StringUtils.substringAfterLast("abcba", "b");//---"a"
StringUtils.substringBetween("tagabctag", "tag");//---"abc"
StringUtils.substringBetween("yabczyabcz", "y", "z");//---"abc"
String string ="http://18.ss360.org:8081//upload/localpath/10000001/20220511/20220511102711431143383619360/20220511102711471424994755491_num.mp4";
String substringBefore = StringUtils.substringAfter(string, "upload");//---"a"
System.out.println("---substringBefore--"+substringBefore);
substringBefore = StringUtils.substringAfter(substringBefore, ".");//---"a"
System.out.println("---substringBefore--"+substringBefore);
int countMatches = StringUtils.countMatches("1.0, 1.0, 2.0, 2.0", "2");//---2
System.out.println(countMatches);
String substringBefore2 = StringUtils.substringBefore("112.1", ".");
System.out.println("---substringBefore2--"+substringBefore2.length());
if(substringBefore2.length()>4) {
System.out.println("---erroe---");
}
String substringAfter = StringUtils.substringAfter("112.122", ".");
System.out.println("---substringBefore2--"+substringAfter.length());
if(substringAfter.length()>2) {
System.out.println("---error");
}
String substringBetween = StringUtils.substringBetween("*liurg*", "*");
System.out.println("----substringBetween--"+substringBetween);
String mid = StringUtils.mid("刘瑞光线下", 0, 8);//---"cdef"
System.out.println("---mid---"+mid);
boolean contains = StringUtils.contains("111", ".");//---false
System.out.println("--contains--"+contains);
Map<String,String> map=new HashMap<>();
boolean containsKey = map.containsKey("toto");
if(containsKey==true) {
System.out.println("---11---");
}
if(containsKey==false) {
System.out.println("---12---");
}
System.out.println("---toto--"+containsKey);
String[] split = StringUtils.split("1.1.", ".");//---["a", "b", "c"]
System.out.println(split.length+"-111222--"+Arrays.toString(split));
String left = StringUtils.left("1.1.12.4.", 2);//---"ab"
System.out.println("---left---"+left);
String[] splitByWholeSeparator = StringUtils.splitByWholeSeparator("1.1.12.4.", ".", 4);
System.out.println("---1---"+Arrays.toString(splitByWholeSeparator));
int num = getNum("1.1.12.4.");
System.out.println(num);
int ordinalIndexOf = StringUtils.ordinalIndexOf("1.1.12.4.", ".", 4);
System.out.println("---"+ordinalIndexOf);
//计算出点的位数
String left2 = StringUtils.left("1.1.12.4.", ordinalIndexOf+1);
System.out.println("--lef--"+left2);
List<String> value = getValue("1.1.12.4.");
System.out.println("--VALUE---"+value);
System.out.println("--截取点前面的值--"+StringUtils.substringBefore("1", "."));
System.out.println("--判断字符串---"+getNum("1."));
}
public static List<String> getValue(String area) {
String[] split = StringUtils.split(area, ".");
List<String> areaId=new ArrayList<String>();
for (int i = 1; i < split.length+1; i++) {
int ordinalIndexOf = StringUtils.ordinalIndexOf(area, ".", i);
//计算出点的位数
String left2 = StringUtils.left(area, ordinalIndexOf+1);
areaId.add(left2);
}
return areaId;
}
public static int getNum(String str) {
List<String> lists=new ArrayList<String>();
//存放每个字符的数组
String [] strs = new String[str.length()];
//计数该字符出现了多少次
int count = 0;
//先把字符串转换成数组
for(int i = 0;i<strs.length;i++){
strs[i] = str.substring(i,i+1);
System.out.println("--strs--"+strs[i]);
}
//挨个字符进行查找,查找到之后count++
for(int i = 0;i<strs.length;i++){
if(strs[i].equals(".")){
count++;
}
}
return count;
}
}
Joiner 可以快速地把多个字符串或字符串数组连接成为用特殊符号连接的字符串。
拼接
List<String> list = Lists.newArrayList("a","b","c");
String value =Joiner.on("-").skipNulls().join(list);
System.out.println(value); //输出为: a-b-c
分割
Splitter用来分割字符串
String testString = "Monday,Tuesday,,Thursday,Friday,,"; //英文分号分割;忽略空字符串 Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults(); System.out.println(splitter.split(testString).toString());
字符串转集合
List<String> list = Splitter.on("#").limit(3).splitToList("hello#world#heh#ss"); System.out.println(list.size());
把map变为stringe
String join = Joiner.on(",").withKeyValueSeparator("=").join(stringStringMap);
System.out.println(join);
转为报文
aaaabbbbccccdddd 相当于报文 result:[aaaa, bbbb, cccc, dddd]
List<String> result = Splitter.fixedLength(4).splitToList("aaaabbbbccccdddd");
System.out.println(result);
System.out.println(result.size());
用的是hutool提供的工具类
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
//List转Json,maps是List类型的参数
String json = JSONUtil.toJsonStr(maps);
System.out.println("这是json字符串: "+json);
//Json转List
JSONArray objects =JSONUtil.parseArray(json);
List<Map> maps1 = JSONUtil.toList(objects, Map.class);
System.out.println("这是list集合: "+maps1);

本文详细介绍了Java中StringUtils类的各种实用方法,包括字符串的修剪、删除空格、截取、替换、判断、比较、填充、分割等操作,以及如何处理字符串中的特定字符和模式。这些方法在日常开发中非常常见,对提升代码效率有很大帮助。
2845

被折叠的 条评论
为什么被折叠?



