The Java. lang package has a string class method: Split ("separator" [, limit]). This method returns an array.
Separator indicates the delimiter and limit indicates the number of elements in the returned array.
Note:
If "." and "|" escape characters exist in the separator, \: Must be added before them \\:
If ". ", must be written as follows: string. split ("\\. "), in this way, the correct separation is not allowed using string. split (". ");
If "|" is used as the separator, it must be written as follows: string. split ("\ |"), in order to correctly separate, cannot use string. split ("| ");
If a string contains multiple separators, you can use "|" as a hyphen, for example, "A = 1 and B = 2 or C = 3 ", you can use string to separate all three. split ("and | or ");
Limit groups the entire string. The grouping element contains all the characters in the original string! Example 2:
Example 1:
Public class splitdemo {
Public static string [] Ss = new string [20];
Public splitdemo (){
String S = "The rain in Spain falls mainly in the plain .";
// Separate each space character.
Ss = S. Split ("");
}
Public static void main (string [] ARGs ){
Splitdemo demo = new splitdemo ();
For (INT I = 0; I <ss. length; I ++)
System. Out. println (ss [I]);
}
}
Program result:
The
Rain
In
Spain
Falls
Mainly
In
The
Plain
Example 2:
Public class splitdemo {
Public static string [] Ss = new string [20];
Public splitdemo (){
String S = "The rain in Spain falls mainly in the plain .";
Ss = S. Split ("", 2); // separate each space character.
}
Public static void main (string [] ARGs ){
Splitdemo demo = new splitdemo ();
For (INT I = 0; I <ss. length; I ++)
System. Out. println (ss [I]);
}
}
Program result:
The
Rain in Spain falls mainly in the plain
Example 3:
Public class splitdemo3 {
Public static string [] Ss = new string [20];
Public splitdemo3 (){
String S = "The rain in Spain falls mainly in the plain .";
Ss = S. Split ("", 20); // separate each space character
}
Public static void main (string [] ARGs ){
Splitdemo3 demo = new splitdemo3 ();
For (INT I = 0; I <ss. length; I ++)
System. Out. println (ss [I]);
}
}
Program result:
The
Rain
In
Spain
Falls
Mainly
In
The
Plain.