apache-commons-lang

拜拜、爱过 提交于 2019-12-07 10:33:30

####This Lang API is an extension to the java.lang package. https://wiki.apache.org/commons/Lang

###Lang aims to provide:

  • Comprehensive String handling utilities
  • Enumerated types (pre JDK 1.5)
  • Nested exceptions (pre JDK 1.4)
  • Builders to create hashCode, equals, toString and compareTo methods
  • Utilities for Object, Date and Numbers 这里的工具类太多了,主要就是各个对象的基本操作. ###依赖
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

###代码示例:

import static org.junit.Assert.assertEquals;  
import static org.junit.Assert.assertFalse;  
import static org.junit.Assert.assertTrue;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import org.apache.commons.lang.RandomStringUtils;  
import org.apache.commons.lang3.ArrayUtils;  
import org.apache.commons.lang3.StringEscapeUtils;  
import org.apache.commons.lang3.StringUtils;  
import org.apache.commons.lang3.text.WordUtils;  
import org.junit.Test;  
import com.zx.common.log.LogUtil;  
      
public class StringUtilsTest {   

    @Test
    public void testIsEmpty() {
        //isEmpty   Checks if a CharSequence is empty ("") or null. 断某字符串是否为空,为空的标准是str null 或 str.length() == 0
        //NOTE: This method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is available in isBlank().
        assertTrue(StringUtils.isEmpty(null)); // true  
        assertTrue(StringUtils.isEmpty("")); // true  
        assertFalse(StringUtils.isEmpty(" ")); // false   这里要注意下
        assertFalse(StringUtils.isEmpty("bob")); // false  
        assertFalse(StringUtils.isEmpty("  bob  ")); // false  

        //isBlank   判断某字符串是否为空或长度为0或由空白符(whitespace)构成 
        assertTrue(StringUtils.isBlank(null)); // true  
        assertTrue(StringUtils.isBlank("")); // true  
        assertTrue(StringUtils.isBlank(" ")); // true  
        assertFalse(StringUtils.isBlank("bob")); // false  
        assertFalse(StringUtils.isBlank("  bob  ")); // false 
    }

    @Test
    public void testTrim() {
        //Removes control characters (char <= 32) from both ends of this String, handling null by returning null. 去掉字符串两端的控制符(control characters, char <= 32)
        assertEquals(null, StringUtils.trim(null)); // null  
        assertEquals("", StringUtils.trim("")); // ""  
        assertEquals("", StringUtils.trim("     ")); // ""  
        assertEquals("abc", StringUtils.trim("abc")); // "abc"  
        assertEquals("abc", StringUtils.trim("    abc")); // "abc"  
        assertEquals("abc", StringUtils.trim("    abc  ")); // "abc"  
        assertEquals("ab c", StringUtils.trim("    ab c  ")); // "ab c"  
    }

    @Test
    public void testStrip() {
        // Strips whitespace from the start and end of a String.
        assertEquals(null, StringUtils.strip(null)); // null  
        assertEquals("", StringUtils.strip("")); // ""  
        assertEquals("", StringUtils.strip("   ")); // ""  
        assertEquals("abc", StringUtils.strip("abc")); // "abc"  
        assertEquals("abc", StringUtils.strip("  abc")); // "abc"  
        assertEquals("abc", StringUtils.strip("abc  ")); // "abc"  
        assertEquals("abc", StringUtils.strip(" abc ")); // "abc"  
        assertEquals("ab c", StringUtils.strip(" ab c ")); // "ab c"  

        //Strips any of a set of characters from the start and end of a String. This is similar to String.trim() but allows the characters to be stripped to be controlled.
        //strip 第二个参数中的每个参数都是要剔除的,不要当作一个整体
        assertEquals("  abc", StringUtils.strip("  abcyx", "xyz")); // "  abc"  
        assertEquals("  abc", StringUtils.strip("  abcyxz", "xyz")); // "  abc"  
        //Strips any of a set of characters from the start of a String.
        assertEquals("abcxyz  ", StringUtils.stripStart("yxabcxyz  ", "xyz")); // "abcxyz  "  
        assertEquals("abcxyz  ", StringUtils.stripStart("yxyxyxabcxyz  ", "xyz ")); // "abcxyz  "  
        assertEquals("abcxyz  ", StringUtils.stripStart(" yxyxyxabcxyz  ", "xyz ")); // "abcxyz  "  
        assertEquals("bcxyz  ", StringUtils.stripStart(" yxyxyxabcxyz  ", "xyz a")); // "abcxyz  "  
        assertEquals("abcxyz  ", StringUtils.stripStart(" yxyxyxabcxyz  ", "xyz b")); // "abcxyz  "  
        assertEquals("  xyzabc", StringUtils.stripEnd("  xyzabcyx", "xyz")); // "  xyzabc"  
    }

    @Test
    public void testsplit() {
        assertEquals(0, StringUtils.split("").length);//[]
        assertEquals("abc", StringUtils.split(" abc ")[0]);//["abc"] 

        //默认半角空格分割  
        String str1 = "aaa bbb ccc";
        String[] dim1 = StringUtils.split(str1); // => ["aaa", "bbb", "ccc"]   

        assertEquals(3, dim1.length);//3  
        assertEquals("aaa", dim1[0]);//"aaa"  
        assertEquals("bbb", dim1[1]);//"bbb"  
        assertEquals("ccc", dim1[2]);//"ccc"  

        //指定分隔符  
        String str2 = ",aaa,bbb,ccc,";
        String[] dim2 = StringUtils.split(str2, ","); // => ["aaa", "bbb", "ccc"]  
        assertEquals(3, dim2.length);//3  
        assertEquals("aaa", dim2[0]);//"aaa"  
        assertEquals("bbb", dim2[1]);//"bbb"  
        assertEquals("ccc", dim2[2]);//"ccc"  

        //去除空字符串  
        String str3 = "aaa,,bbb";
        String[] dim3 = StringUtils.split(str3, ","); // => ["aaa", "bbb"]  

        assertEquals(2, dim3.length);//2  
        assertEquals("aaa", dim3[0]);//"aaa"  
        assertEquals("bbb", dim3[1]);//"bbb"  

        //包含空字符串  
        String str4 = "aaa,,bbb";
        String[] dim4 = StringUtils.splitPreserveAllTokens(str4, ","); // => ["aaa", "", "bbb"]  

        assertEquals(3, dim4.length);//3  
        assertEquals("aaa", dim4[0]);//"aaa"  
        assertEquals("", dim4[1]);//""  
        assertEquals("bbb", dim4[2]);//"bbb"  

        //指定分割的最大次数(超过后不分割)  
        String str5 = "aaa,bbb,ccc";
        String[] dim5 = StringUtils.split(str5, ",", 2); // => ["aaa", "bbb,ccc"]  

        assertEquals(2, dim5.length);//2  
        assertEquals("aaa", dim5[0]);//"aaa"  
        assertEquals("bbb,ccc", dim5[1]);//"bbb,ccc"  
    }

    @Test
    public void testJoin() {
        //数组元素拼接  
        String[] array = {"aaa", "bbb", "ccc"};
        String result1 = StringUtils.join(array, ",");

        assertEquals("aaa,bbb,ccc", result1);//"aaa,bbb,ccc"  

        //集合元素拼接  
        List<String> list = new ArrayList<String>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        String result2 = StringUtils.join(list, ",");
        assertEquals("aaa,bbb,ccc", result2);//"aaa,bbb,ccc"  
    }

    @Test
    public void testEscape() {
        assertEquals("测试测试哦", StringEscapeUtils.escapeCsv("测试测试哦"));//"测试测试哦"  
        assertEquals("\"测试,测试哦\"", StringEscapeUtils.escapeCsv("测试,测试哦"));//"\"测试,测试哦\""  
        assertEquals("\"测试\n测试哦\"", StringEscapeUtils.escapeCsv("测试\n测试哦"));//"\"测试\n测试哦\""  

        assertEquals("测试测试哦", StringEscapeUtils.escapeHtml4("测试测试哦"));//"<p>测试测试哦</p>"  
        //StringEscapeUtils.escapeJava
        //StringEscapeUtils.escapeEcmaScript
        //StringEscapeUtils.escapeXml
        assertEquals("He didn't say, \\\"Stop!\\\"", StringEscapeUtils.escapeJava("He didn't say, \"Stop!\""));//"\"rensaninng\"\uFF0C\u6B22\u8FCE\u60A8\uFF01"  

        assertEquals("He didn\\\'t say, \\\"Stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"Stop!\""));//"\u6D4B\u8BD5\'\u6D4B\u8BD5\u54E6"  
    }

    @Test
    public void testRandom() {
        // 10位英字  
        assertEquals(10, RandomStringUtils.randomAlphabetic(10).length());

        // 10位英数  
        assertEquals(10, RandomStringUtils.randomAlphanumeric(10).length());

        // 10位ASCII码  
        assertEquals(10, RandomStringUtils.randomAscii(10).length());

        // 指定文字10位  
        assertEquals(10, RandomStringUtils.random(10, "abcde").length());
        LogUtil.get(this.getClass()).debug(RandomStringUtils.randomAlphabetic(10));
        LogUtil.get(this.getClass()).debug(RandomStringUtils.randomAlphanumeric(10));
        LogUtil.get(this.getClass()).debug(RandomStringUtils.randomAscii(10));
        LogUtil.get(this.getClass()).debug(RandomStringUtils.random(10, "abced"));
        LogUtil.get(this.getClass()).debug(RandomStringUtils.random(10));
        LogUtil.get(this.getClass()).debug(RandomStringUtils.randomNumeric(10));
    }

    @Test
    public void testArray() {
        // 追加元素到数组尾部  
        int[] array1 = {1, 2};
        array1 = ArrayUtils.add(array1, 3); // => [1, 2, 3]  

        assertEquals(3, array1.length);//3  
        assertEquals(3, array1[2]);//3  

        // 删除指定位置的元素  
        int[] array2 = {1, 2, 3};
        array2 = ArrayUtils.remove(array2, 2); // => [1, 2]  

        assertEquals(2, array2.length);//2  

        // 截取部分元素  
        int[] array3 = {1, 2, 3, 4};
        array3 = ArrayUtils.subarray(array3, 1, 3); // => [2, 3]  

        assertEquals(2, array3.length);//2  

        // 数组拷贝  
        String[] array4 = {"aaa", "bbb", "ccc"};
        String[] copied = (String[]) ArrayUtils.clone(array4); // => {"aaa", "bbb", "ccc"}  

        assertEquals(3, copied.length);//3         

        // 判断是否包含某元素  
        String[] array5 = {"aaa", "bbb", "ccc", "bbb"};
        boolean result1 = ArrayUtils.contains(array5, "bbb"); // => true       
        assertTrue(result1);//true  

        // 判断某元素在数组中出现的位置(从前往后,没有返回-1)  
        int result2 = ArrayUtils.indexOf(array5, "bbb"); // => 1       
        assertEquals(1, result2);//1  
        result2 = ArrayUtils.indexOf(array5, "bbbb"); // => 1       
        assertEquals(-1, result2);//1  

        // 判断某元素在数组中出现的位置(从后往前,没有返回-1)  
        int result3 = ArrayUtils.lastIndexOf(array5, "bbb"); // => 3  
        assertEquals(3, result3);//3  

        // 数组转Map  
        Map<Object, Object> map = ArrayUtils.toMap(new String[][] {{"key1", "value1"}, {"key2", "value2"}});
        assertEquals("value1", map.get("key1"));//"value1"  
        assertEquals("value2", map.get("key2"));//"value2"  

        // 判断数组是否为空  
        Object[] array61 = new Object[0];
        Object[] array62 = null;
        Object[] array63 = new Object[] {"aaa"};

        assertTrue(ArrayUtils.isEmpty(array61));//true  
        assertTrue(ArrayUtils.isEmpty(array62));//true  
        assertTrue(ArrayUtils.isNotEmpty(array63));//true  

        // 判断数组长度是否相等  
        Object[] array71 = new Object[] {"aa", "bb", "cc"};
        Object[] array72 = new Object[] {"dd", "ee", "ff"};

        assertTrue(ArrayUtils.isSameLength(array71, array72));//true  

        //        // 判断数组元素内容是否相等  
        //        Object[] array81 = new Object[] {"aa", "bb", "cc"};
        //        Object[] array82 = new Object[] {"aa", "bb", "cc"};
        //        assertEquals("", ArrayUtils.isEquals(array81, array82));

        // Integer[] 转化为 int[]  
        Integer[] array9 = new Integer[] {1, 2};
        int[] result = ArrayUtils.toPrimitive(array9);

        assertEquals(2, result.length);//2  
        assertEquals(1, result[0]);//1  

        // int[] 转化为 Integer[]   
        int[] array10 = new int[] {1, 2};
        Integer[] result10 = ArrayUtils.toObject(array10);

        assertEquals(2, result.length);//2  
        assertEquals(1, result10[0].intValue());//1  
    }

    @Test(expected = IllegalArgumentException.class)
    public void testAbbreviateException() {
        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 3));
    }

    @Test
    public void testAbbreviate() {
        //对长字符串中的多余指定位数用 省略号表示 , Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."
        //Specifically:
        //•If the number of characters in str is less than or equal to maxWidth, return str.
        //•Else abbreviate it to (substring(str, 0, max-3) + "...").
        //•If maxWidth is less than 4, throw an IllegalArgumentException.
        //•In no case will it return a String of length greater than maxWidth.
        assertEquals("Pl...", StringUtils.abbreviate("Please check the logs for an error.", 5));
        assertEquals("Please...", StringUtils.abbreviate("Please check the logs for an error.", 9));
        assertEquals("Please ...", StringUtils.abbreviate("Please check the logs for an error.", 10));
        assertEquals(null, StringUtils.abbreviate(null, 1));
        assertEquals("abc...", StringUtils.abbreviate("abcdefg", 6));
        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 7));
        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8));
        assertEquals("abcdefg", StringUtils.abbreviate("abcdefg", 8));
    }

    @Test
    public void testcapitalize() {
        // 首字符大写
        assertEquals("Jakarta commons", StringUtils.capitalize("jakarta commons"));
        assertEquals(null, StringUtils.capitalize(null));
        assertEquals("", StringUtils.capitalize(""));
        assertEquals("Cat", StringUtils.capitalize("cat"));
        assertEquals("CAt", StringUtils.capitalize("cAt"));
        assertEquals("'cat'", StringUtils.capitalize("'cat'"));
    }

    @Test
    public void testwordcapitalize() {
        // 首字符大写,这个是针对一个句子中的所有的字符的
        assertEquals("Jakarta Commons", WordUtils.capitalize("jakarta commons"));
        assertEquals("I Am FINE", WordUtils.capitalize("i am FINE"));//WordUtils.capitalize("i am FINE") = "I Am FINE"
        assertEquals("Jakarta Commons", WordUtils.capitalizeFully("jakarta COMMONS"));
        assertEquals("I Am Fine", WordUtils.capitalizeFully("i am FINE"));
    }

    @Test
    public void testcenter() {
        // 字符居中
        assertEquals("   java   ", StringUtils.center("java", 10));
    }

    @Test
    public void testreplace() {
        // 字符替换
        assertEquals("This is a illustration for replace and overlay feature", StringUtils.replace("This is a demo for replace and overlay feature", "demo", "illustration"));
        String message = "Your password is: somepassword";
        assertEquals("Your password is: *****", StringUtils.overlay(message, "*****", 18, message.length()));
    }

    @Test
    public void testrepeat() {
        // 字符重复
        assertEquals("abcabc", StringUtils.repeat("abc", 2));
    }

    @Test
    public void testUpper() {
        // 字符大小写判断
        assertTrue(StringUtils.isAllLowerCase("abcabc"));
        assertTrue(StringUtils.isAllUpperCase("ABCABC"));
    }
    
    @Test
    public void testZc() {
        // 字符组成判断
        assertTrue(StringUtils.isAlphanumericSpace("abcabc"));
        assertTrue(StringUtils.isAlphanumericSpace("abcabc123 "));
        assertFalse(StringUtils.isAlphaSpace("abcabc123 "));
        assertTrue(StringUtils.isAlphanumeric("abcabc123"));
        assertFalse(StringUtils.isNumeric("abcabc123"));
        assertTrue(StringUtils.isAlpha("ABCABC"));
        assertTrue(StringUtils.isNumericSpace("123 "));
        assertTrue(StringUtils.isAsciiPrintable("123 "));
        assertTrue(StringUtils.isWhitespace(" "));
    }
    
    @Test
    public void testOther() {
        // 其它判断
        assertEquals(4,StringUtils.countMatches("ababsssababa", "ab"));//小字符串在大字符串中的匹配次数
        assertEquals("fedcba",StringUtils.reverse("abcdef"));//字符串倒转
        assertEquals("i AM A-a*A",StringUtils.swapCase("I am a-A*a") );//大小写转换,空格不动 
        assertEquals("abcTTT",StringUtils.rightPad("abc", 6, 'T') );//在右边加下字符,使之总长度为6
        assertEquals("ab",StringUtils.left("abc", 2));//取得一个字符串左边的两个字符
        assertEquals("bc",StringUtils.right("abc", 2));//取得一个字符串右边的两个字符
        assertTrue(StringUtils.contains("abc", "ab"));//判断是否包含这个字符
    }

    
}

2016-11-06 15:32:41 星期日

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!