Two ways of java string interception Explain the two ways of java string interception

Two ways to intercept java strings

1.split()+regular expression to intercept. 

The prototype of the String.split() method is: public String[] split(String regex, int limit)

The split function is used to separate a string into an array of strings using a specific delimiter (regex), and the function returns an array . Decomposition is done at each location where the regex occurs.
It should be noted that there are the following points:
(1) regex is optional. A string or regular expression object that identifies whether one or more characters are used to delimit the string. If this option is omitted, a single-element array containing the entire string is returned.
(2) limit is also optional. This value is used to limit the number of elements in the returned array.
(3) Pay attention to escape characters: "." and "|" are escape characters, and "\\" must be added. The same goes for * and +.
   If "." is used as the separator, it must be written as follows:
   String.split("\\."), so that the separation can be performed correctly, and String.split(".");

( 4) If in a There are multiple separators in the string, you can use "|" as a hyphen, for example: "acountId=? and act_id =? or extra=?", to separate all three, you can use

  String.split("and|or"); However, intercepting in this way will have a great performance loss, because analyzing the regularity is very time-consuming

2. String interception is performed by the subString() method. subString provides different interception methods through different  parameters. You can pass only one parameter, or you can pass two parameters. When two parameters are used, the head and tail are ignored. 

 
   
import java.util. *;
public class Demo {
	public static void main(String[] args) {
		String str = "abc,12,csdn,666.cd";
		String[]  strs=str.split(",");
		Demo re=new Demo();
		re.print(strs);
		
		System.out.println("***********");
		String[]  strs2=str.split("\\.");
		re.print(strs2);
		
		System.out.println("***********");
		String[]  strs3=str.split(",|\\.");
		re.print(strs3);
		
		System.out.println("***********");
		System.out.println(str.substring(2));//A parameter
		System.out.println(str.substring(2,7));//Two parameters
		
	}
	public static void print(String[] strs) {
		for(int i=0,len=strs.length;i<len;i++){
		    System.out.println(strs[i].toString());
		}
	}
}
operation result:
abc
12
csdn
666.cd
***********
abc,12,csdn,666
cd
***********
abc
12
csdn
666
cd
***********
c,12,csdn,666.cd
c,12,


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325886104&siteId=291194637