I. Overview
Providing the basic operation of the string
Second, the use
2.1, string concatenation
Guava string concatenation method is employed class Joiner
@Test public void testJdkJoin () { List <String> strlist = Lists.newArrayList ( ". 1", "2", null , ". 3", ". 4" ); // string concatenation, not Skip empty string String = String.Join STR ( "," , strlist); Assert.assertEquals ( "1,2,3,4" , STR); } @Test public void testGuavaJoin () { List <String> strlist = Lists.newArrayList ( " . 1 "," 2 ", null ,". 3 ",". 4 " ); // string concatenation, skip empty string string str = Joiner.on(",").skipNulls().join(strList);on("," Assert.assertEquals("1,2,3,4", str); }
2.2 String split
@Test public void testJdkSplit(){ String str = "1,2, 3 ,,4,"; //trimResults():去除空格,omitEmptyStrings():删除空数组 String[] strList = str.split(","); // List<String> strList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(str); for (int i = 0; i < strList.length; i++) { String s = strList[i]; System.out.println(s); } Assert.assertEquals(4,strList.length); } @Test public void testGuavaSplit () { String STR = "1,2,. 3 ,,. 4," ; // trimResults (): removing spaces, omitEmptyStrings (): Delete empty array List <String> strlist = Splitter.on ( "," ) .trimResults () omitEmptyStrings () splitToList (STR);.. strList.forEach (S -> System.out.println (S)); Assert.assertEquals ( . 4 , strList.size ()); }
2.3, jdk string search method using []
@Test public void testSearch () { String STR = "abcdef" ; // contains the string CD Assert.assertEquals ( to true , str.contains ( "CD" )); // find the beginning of the string abc Assert.assertEquals ( to true , str.startsWith ( "ABC" )); // Find string ending DEF Assert.assertEquals ( to true , str.endsWith ( "DEF" )); }
2.4, the string conversion
@Test public void testConversion () { String STR = "abcdef" ; String newStr = str.replace ( "BCDE", "Hello" ); System.out.println (newStr); Assert.assertEquals ( "ahellof" , newStr) ; String str2 = "the ABC ABC 123" ; // print digital System.out.println (. CharMatcher.digit () retainFrom (str2)); // print lowercase . System.out.println (CharMatcher.javaLowerCase () retainFrom (str2)); // print capital letters . System.out.println (CharMatcher.javaUpperCase () retainFrom ( str2));// print all letters System.out.println (CharMatcher.javaLetter () retainFrom (str2).); // replace the extra spaces into one space System.out.println (CharMatcher.whitespace () trimAndCollapseFrom (str2 , '. ' )); // statistical letter appears . System.out.println (String.valueOf (CharMatcher.javaLetter () Countin (str2))); }
Export
ahellof 123 abc ABC ABCabc ABC abc 123 6
Hair