You often need to use java to split strings such as 1, 2, 3, 4 tom, jim, andy, and han.
1. The syntax is as follows:
String. split (sourceStr, maxSplit)
String. split (sourceStr)
Parameter description: sourceStr is the split string, and maxSplit is the maximum split number.
Return value description: the return value of the split function is a String array String [].
Example
The code is as follows: |
Copy code |
Package com. java. lang; Public class StringSp { /** * @ Param args */ Public static void main (String [] args ){ // TODO Auto-generated method stub Java. lang. String a = "my name is yuexiaosheng my blog is java-er.com "; // String splitting algorithm of java. lang. String String [] arr = a. split (""); For (int I = 0; I <arr. length; I ++ ){ System. out. println (I + "" + arr [I]); } String B = "green | red | blue | black "; // String splitting algorithm of java. lang. String Arr = B. split ("| "); System. out. println ("split the reef -------------------------------------------"); For (int I = 0; I <arr. length; I ++ ){ System. out. println (I + "" + arr [I]); } System. out. println ("split the reef -------------------------------------------"); Arr = B. split ("\\| "); For (int I = 0; I <arr. length; I ++ ){ System. out. println (I + "" + arr [I]); } } }
0 my 1 name 2 is 3 yuexiaosheng 4 my 5 blog 6 is 7 java-er.com Split reef --------------- 0 1g 2 r 3 e 4 e 5 n 6 | 7 r 8 e 9 d 10 | 11 B 12 l 13 u 14 e 15 | 16 B 17 l 18 19 c 20 k Split reef --------------- 0 green 1 red 2 blue 3 black |
In conclusion, some strings must be escaped. Otherwise, the characters are separated by null.
Some precautions
1. If ". ", must be written as follows: String. split ("\\. "), in this way, the correct separation is not allowed using String. split (". ");
2. If "|" is used as the separator, it must be written as follows: String. split ("\ |"), in order to correctly separate, cannot use String. split ("| ");
"." And "|" are escape characters and must be added "\\";
3. 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 ");