StringUtils常用方法

处理文本对Java应用来说应该算是家常便饭了,在1.4出现之前,Java自身提供的API非常有限,如String、StringTokenizer、StringBuffer,操作也比较单一。无非就是查找substring、分解、合并等等。到1.4的出现可以说Java的文字处理上了一个台阶,因为它支持regular expression了。这可是个重量级而方便的东东啊,缺点是太复杂,学习起来有一定难度。相较而言,Jakarta Commons提供的StringUtils和WordUtils至今还维持着那种简洁而强大的美,使用起来也很顺手。来看一个例子:



package sean.study.jakarta.commons.lang;

import org.apache.commons.lang.StringUtils;

public class StringUtilsAndWordUtilsUsage {

    public static void main(String[] args) {
        // data setup
        String str1 = "";
        String str2 = " ";
        String str3 = "\t";
        String str4 = null;
        String str5 = "123";
        String str6 = "ABCDEFG";
        String str7 = "It feels good to use Jakarta Commons.\r\n";

        
        // check for empty strings
        System.out.println("==============================");
        System.out.println("Is str1 blank? " + StringUtils.isBlank(str1));
        System.out.println("Is str2 blank? " + StringUtils.isBlank(str2));
        System.out.println("Is str3 blank? " + StringUtils.isBlank(str3));
        System.out.println("Is str4 blank? " + StringUtils.isBlank(str4));

        
        // check for numerics
        System.out.println("==============================");
        System.out.println("Is str5 numeric? " + StringUtils.isNumeric(str5));
        System.out.println("Is str6 numeric? " + StringUtils.isNumeric(str6));

        
        // reverse strings / whole words
        System.out.println("==============================");
        System.out.println("str6: " + str6);
        System.out.println("str6 reversed: " + StringUtils.reverse(str6));
        System.out.println("str7: " + str7);
        String str8 = StringUtils.chomp(str7);
        str8 = StringUtils.reverseDelimited(str8, ' ');
        System.out.println("str7 reversed whole words : \r\n" + str8);      
        // build header (useful to print log messages that are easy to locate)
        System.out.println("==============================");
        System.out.println("print header:");
        String padding = StringUtils.repeat("=", 50);
        String msg = StringUtils.center(" Customised Header ", 50, "%");
        Object[] raw = new Object[]{padding, msg, padding};
        String header = StringUtils.join(raw, "\r\n");
        System.out.println(header);
    }
}



输出的结果如下:



==============================

Is str1 blank? true

Is str2 blank? true

Is str3 blank? true

Is str4 blank? true

==============================

Is str5 numeric? true

Is str6 numeric? false

==============================

str6: ABCDEFG

str6 reversed: GFEDCBA

str7: It feels good to use Jakarta Commons.



str7 reversed whole words :

Commons. Jakarta use to good feels It

==============================

print header:

==================================================

%%%%%%%%%%%%%%% Customised Header %%%%%%%%%%%%%%%%

==================================================

你可能感兴趣的:(apache)