Three methods of java string interception are recommended by of

  • 2020-05-19 04:49:27
  • OfStack

As you know, java provides many ways to intercept strings. Let's take a look at some of them.

1.split()+ regular expression to intercept.

Pass the regex into split(). Returns an array of strings. However, interception in this way can be very expensive in terms of performance, because parsing the regex is very time consuming.


String str = "abc,12,3yy98,0";
String[] strs=str.split(",");
for(int i=0,len=strs.length;i<len;i++){
  System.out.println(strs[i].toString());
}

Operation results:

abc
12
3yy98
0

2. String interception via the subString() method.

subString provides different interception methods with different parameters

2.1 only one parameter is passed

Such as:

String sb = "bbbdsajjds";
sb.substring(2);

Intercepts a string from the index number 2 to the end of the string. (index values start at 0);

2.2 pass in two index values

String sb = "bbbdsajjds";
sb.substring(2, 4);

Start at index number 2 and end at index number 4 (and do not include index 4 interception, that is, the actual interception is 2 and 3 characters);

The results are as follows:

bdsajjds
bd

3. The method provided by StringUtils

StringUtils. substringBefore (" dskeabcee ", "e");
/ the result is: dsk/
Here is the first "e" as the standard.

StringUtils. substringBeforeLast (" dskeabcee ", "e")
The result is: dskeabce

Here, the last "e" shall prevail.


Related articles: