在编程中,我们可能会经常操作字符串,为了简便起见,Guava中为我们封装了若干的简单操作方法,下面我就是以实用为目的,简单的介绍一下字符串的拼接、分割、查找与变换。
字符串的拼接采用的是Guava中的Joiner类中的方法,用法如下:
@Test
public void testJoin(){
List<String> strList = Lists.newArrayList("1","2",null,"3","4");
//字符串拼接,跳过空字符串
String str = Joiner.on(",").skipNulls().join(strList);
log.info(str);
Assert.assertEquals("1,2,3,4",str);
}
显示结果:
1,2,3,4
字符串分割采用的是Guava中的Splitter类中的方法,用法如下:
@Test
public void testSplit(){
String str = "1,2, 3 ,,4,";
//trimResults():去除空格,omitEmptyStrings():删除空数组
List<String> strList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(str);
strList.forEach(s -> log.info(s));
Assert.assertEquals(4,strList.size());
}
显示结果:
2018-03-03 22:03:42 INFO main com.lyc.StringOperationTest.lambda$testSplit$0(StringOperationTest.java:36) - 1
2018-03-03 22:03:42 INFO main com.lyc.StringOperationTest.lambda$testSplit$0(StringOperationTest.java:36) - 2
2018-03-03 22:03:42 INFO main com.lyc.StringOperationTest.lambda$testSplit$0(StringOperationTest.java:36) - 3
2018-03-03 22:03:42 INFO main com.lyc.StringOperationTest.lambda$testSplit$0(StringOperationTest.java:36) - 4
这个采用的仍然是原始的jdk中的方法:
@Test
public void testSearch(){
String str = "abcdef";
//包含字符串cd
Assert.assertEquals(true,str.contains("cd"));
//查找以abc开头的字符串
Assert.assertEquals(true,str.startsWith("abc"));
//查找以def结尾的字符串
Assert.assertEquals(true,str.endsWith("def"));
}
字符串变换采用的是Guava中的CharMatcher类中的方法,用法如下:
@Test
public void testConversion(){
String str = "abcdef";
String newStr = str.replace("bcde","hello");
log.info(newStr);
Assert.assertEquals("ahellof",newStr);
String str2 = "ABC abc 123";
//打印数字
log.info(CharMatcher.JAVA_DIGIT.retainFrom(str2));
//打印小写字母
log.info(CharMatcher.JAVA_LOWER_CASE.retainFrom(str2));
//打印大写字母
log.info(CharMatcher.JAVA_UPPER_CASE.retainFrom(str2));
//打印所有字母
log.info(CharMatcher.JAVA_LETTER.retainFrom(str2));
//将多余的空格替换成一个空格
log.info(CharMatcher.whitespace().trimAndCollapseFrom(str2,' '));
//统计出现的字母
log.info(String.valueOf(CharMatcher.JAVA_LETTER.countIn(str2)));
}
显示结果:
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:61) - ahellof
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:65) - 123
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:67) - abc
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:69) - ABC
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:71) - ABCabc
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:73) - ABC abc 123
2018-03-03 22:06:32 INFO main com.lyc.StringOperationTest.testConversion(StringOperationTest.java:75) - 6
源码:string-operation-parent