Split method of string class
Although regular expressions can be used to parse, extract, and replace strings, some methods provided by the string class can be used for some simple applications, the most prominent part is the split method.
The split method can easily split strings according to certain rules.
For example, for the following string:
Tom, Jane, Tony, Elva, Gigi
You only need to call the following code to extract the names:
String value = "Tom, Jane, Tony, Elva, Gigi ";
String [] names = value. Split (",");
For (INT I = 0, n = names. length; I <n; I ++)
{
System. Out. println (Names [I]);
}
Running result:
Tom
Jane
Tony
Elva
Gigi
Many people think that the split method is to split the string according to the given string, knowing that the following problem has been encountered.
There is a string: China. Beijing. Haidian. xuanyuan Road. Parse this string and print the output "Haidian university Road, Beijing, China ".
Write the following code:
String value = "China. Beijing. Haidian. xuanyuan Road ";
String [] names = value. Split (".");
For (INT I = 0, n = names. length; I <n; I ++)
{
System. Out. Print (Names [I] + "");
}
Running result:
Yes. No error! No output!
Let's take a look at the method signature of the split method:
Public String [] Split (string RegEx)
The parameter name here is RegEx, that is, regular expression (regular expression ). This parameter is not a simple delimiter, but a regular expression. After reading the implementation code of the split method, we are more confident:
Public String [] Split (string RegEx, int limit ){
Return Pattern. Compile (RegEx). Split (this, limit );
}
The split method of the matcher class directly called by the split implementation. Readers already know that "." has special meanings in regular expressions, so we must escape it when using it.
The modification code is as follows:
Private Static void split2 ()
{
String value = "China. Beijing. Haidian. xuanyuan Road ";
String [] names = value. Split ("\\.");
For (INT I = 0, n = names. length; I <n; I ++)
{
System. Out. Print (Names [I] + "");
}
}
Running result:
Haidian College Road, Beijing, China