Skip to main content
 首页 » 编程设计

Java 干掉你的StringUtils字符工具类

2022年07月19日150java哥

干掉你的StringUtils字符工具类

可能每个java开发者都写过自己的StringUtils类,主要是java字符串处理非常频繁,但java.lang.String类提供的功能有限。

既然几乎每个人多需要字符串工具类,而jdk也没有提供,所有很多第三方提供了非常好用的工具类。代表性有Apache Commons 中的org.apache.commons.lang3.StringUtils,版本3需要java5及以上版本; Google Guava 中的 com.google.common.base包下面的类,主要有连接、分割、字符匹配和字处理等; Spring framework 中的 org.srpingframework.util.StringUtils,其提供了超过40个静态方法,用于字符串解析和操作。

先简单介绍下apache和google的类,spring的有机会再整理。

apache commons StringUtils

SplitString

import org.apache.rumons.lang.StringUtils; 
 
public classMainClass { 
 
    public static void main(String[] args) { 
 
        //Split a String intoan Array using # as seperator. 
 
        String [] splitArr=StringUtils.split("AB#CD#EF#GH","#"); 
 
  
 
        for(int i=0; i<splitArr.length; i++ ) { 
 
            System.out.println( i + ") "+splitArr[i]); 
 
        } 
 
    } 
 
}


0)AB

1)CD

2)EF

3)GH

StringEscape

import org.apache.rumons.lang.StringEscapeUtils; 
 
public classMainClass { 
 
    public static void main(String[] args) { 
 
        StringstrHTMLInput = "<P>MyName<P>"; 
 
        StringstrEscapeHTML = StringEscapeUtils.escapeHtml(strHTMLInput); 
 
        String strUnEscapeHTML= StringEscapeUtils.unescapeHtml(strEscapeHTML); 
 
        System.out.println("Escaped HTML >>> " +strEscapeHTML); 
 
        System.out.println("UnEscaped HTML >>> " +strUnEscapeHTML); 
 
    } 
 
}


StringUtils.abbreviate

import org.apache.rumons.lang.StringUtils; 
 
public classMainClass { 
 
    public static void main(String[] args) { 
 
        //String can be max 12chars including the ... 
 
        System.out.println("1) Abbreviate Once upon a time >>>" + 
 
            StringUtils.abbreviate("Once upon a time ", 12)); 
 
    } 
 
}


1)Abbreviate Once upon a time >>>Once upon...

StringUtils.chomp

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Remove the specifiedstring at the end of String

      System.out.println("3) Chomp END >>>" +

          StringUtils.chomp("A test String END", "END"));

    }

}

3)Chomp END >>>A test String

StringUtils.containsNone

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Check that a stringdoes not contain any of these characters !@#$%^&*

      System.out.println("14) Check that ABCD contains none of !@#$%^&*>>>" +

          StringUtils.containsNone("ABCD", "!@#$%^&*"));

    }

}

14)Check that ABCD contains none of !@#$%^&* >>>true

StringUtils.containsOnly

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Check if stringcontains only a specified set of characters. Return boolean

      System.out.println("4) Check if 643287460 contains only 0123456789>>>" +

          StringUtils.containsOnly("643287460", "0123456789"));

    }

}

4)Check if 643287460 contains only 0123456789 >>>true

StringUtils.defaultString

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Takes Object input andreturns Empty String if null.

      System.out.println("6) Return default string >>>" + "**" +

          StringUtils.defaultString(null) + "**");

    }

}

6)Return default string >>>****

StringUtils.difference

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Compare two strings.Case Sensitive

      System.out.println("5) Compare ABCDEFG and ABCdefg >>>" +

          StringUtils.difference("ABCDEFG", "ABCdefg"));

    }

}

5)Compare ABCDEFG and ABCdefg >>>defg

StringUtils.equals

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Compare Strings...NoNullPointer Exception!

      System.out.println("12) Comapre null and null >>>" +

          StringUtils.equals(null, null));

    }

}

12)Comapre null and null >>>true

StringUtils.indexOfDifference

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Returns index where theStrings start to differ

      System.out.println(

          "2) Index OfDifference between ABCXYZ and ABCPQR >>>" +

          StringUtils.indexOfDifference("ABCXYZ", "ABCPQR"));

    }

}

2)Index Of Difference between ABCXYZ and ABCPQR >>>3

StringUtils.join

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Join all Strings in theArray into a Single String, separated by $#$

      System.out.println("7) Join Strings using separator >>>" +

          StringUtils.join(new String[] { "AB","CD", "EF" }, "$#$"));

    }

}

7)Join Strings using separator >>>AB$#$CD$#$EF

StringUtils.reverse

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Reverse a String

      System.out.println("9) Reverse >>>" +StringUtils.reverse("REVERSE"));

    }

}

9)Reverse >>>ESREVER

StringUtils.stripToEmpty

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //Strip whitespace fromstart and end of the string.

      //If null returns emptystring

      System.out.println("13) Strip whitespace >>>" +

          StringUtils.stripToEmpty("    ABCD      "));

    }

}

13)Strip whitespace >>>ABCD

StringUtils.substring

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //SubString

      System.out.println("8) Substring >>>" +

          StringUtils.substring("SUBSTRING", 1, 5));

    }

}

8)Substring >>>UBST

StringUtils.trim

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //No NullPointerException even if null!

      System.out.println("10) Trim String. No NullPointerException >>>"+

          StringUtils.trim(null));

    }

}

10)Trim String. No NullPointerException >>>null

StringUtils.trimToEmpty

import org.apache.rumons.lang.StringUtils;

public classMainClass {

    public static void main(String[] args) {

      //If string is null,empty string returned. Else returns trimmed string

      System.out.println("11) Empty String >>>" +

          StringUtils.trimToEmpty(null) + "<<<");

    }

}

11)Empty String >>><<<

Google Guava Splitter

分割字符串的两种方式

// Apache StringUtils...

String[] tokens1 =StringUtils.split("one,two,three",',');

 

// Guava splitter...

Iterable<String> tokens2= Splitter.on(',').split("one,two,three");

Splitter更加面向对象,你首先需要创建一个splitter对象,然后使用其做分割,apache则直接通过static方法实现。

然而Splitter具有可重用性,看下面的示例。

Splitter niceCommaSplitter =Splitter.on(',').omitEmptyString().trimResults();

niceCommaSplitter.split("one,,two,  three"); //"one","two","three"

niceCommaSplitter.split(" four  ,  five  "); //"four","five"

更重要的是,splitter的效率更高。

final String numberList ="One,Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten";

long start =System.currentTimeMillis(); 

for(int i=0; i<1000000;i++) {

    StringUtils.split(numberList, ',');  

}

System.out.println(System.currentTimeMillis()- start);

   

start =System.currentTimeMillis();

for(int i=0; i<1000000;i++) {

    Splitter.on(',').split(numberList);

}

System.out.println(System.currentTimeMillis()- start);

 

在我电脑上返回下面的结果:

594

31

结论:显然,尽量使用splitter.


本文参考链接:https://blog.csdn.net/neweastsun/article/details/52315775
阅读延展