Apache Commons-Lang 簡介

來源:互聯網
上載者:User

標籤:stringutils   apache commons   commons-lang   

一、前言

    Java碼農不識Apache,敲盡一生也枉然。旗下的開源項目眾多,各個都是吊炸天。今日且說Commons,輕輕點擊此連結進入Apache Commons首頁,Logging、Pool、Net、ONGL、EL、IO、DBCP、Email、Collection、Lang……等等項目中常用到的包。而這篇文章的主角Lang則是我們最常用的工具作為jdk的補充,怎能不去詳細探究一番!


    :http://commons.apache.org/proper/commons-lang/download_lang.cgi


二、字串的處理類(StringUtils)

    org.apache.commons.lang3.StringUtils 繼承Object,Operations on String that are null safe。所謂的null safe就是對String進行操作不會出現NullPointerException異常,很實用有沒有!以後再也不怕到處出現null 指標異常了。先看看官方文檔中這個類都有些什麼方法:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/49/9E/wKiom1QWyv7wXBz4AAU5PodFOcs211.jpg" title="QQ圖片20140915191747.jpg" alt="wKiom1QWyv7wXBz4AAU5PodFOcs211.jpg" />

    這些方法基本上看方法名,就能猜出它大概的作用了。

//縮短到某長度,用...結尾.其實就是(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.deleteWhitespace("   ab  c  ");//---"abc"                //比較兩字串,返回不同之處。確切的說是返回第二個參數中與第一個參數所不同的字串        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"


三、其它類簡介

    RandomStringUtils:

        //隨機產生n位元數字        RandomStringUtils.randomNumeric(n);        //在指定字串中產生長度為n的隨機字串        RandomStringUtils.random(n, "abcdefghijk");        //指定從字元或數字中產生隨機字串        System.out.println(RandomStringUtils.random(n, true, false));          System.out.println(RandomStringUtils.random(n, false, true));

    NumberUtils:

        //從數組中選出最大值
        NumberUtils.max(new int[] { 1, 2, 3, 4 });//---4
        //判斷字串是否全是整數
        NumberUtils.isDigits("153.4");//--false
        //判斷字串是否是有效數字
        NumberUtils.isNumber("0321.1");//---false   

    ArrayUtils:

        //建立數組        String[] array = ArrayUtils.toArray("1", "2");        //判斷兩個資料是否相等,如果內容相同, 順序相同 則返回 true        ArrayUtils.isEquals(arr1,arr2);        //判斷數組中是否包含某一對象        ArrayUtils.contains(arr, "33");        //二維數群組轉換成MAP        Map map = ArrayUtils.toMap(new String[][] {                 { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } });

    DateUtils:

        //日期加n天        DateUtils.addDays(new Date(), n);        //判斷是否同一天        DateUtils.isSameDay(date1, date2);        //字串時間轉換為Date        DateUtils.parseDate(str, parsePatterns);


四、結語

    本文只是簡單的介紹了commons-lang中的一些常用工具類,還有許多挺實用的就不一一列舉。還是要自己去查閱文檔試用了才能體會到它的簡便。


    

本文出自 “學而思” 部落格,請務必保留此出處http://linhongyu.blog.51cto.com/6373370/1553329

Apache Commons-Lang 簡介

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.