1 / 2100%
The split method of the String can be used to extract substrings from a string based on certain
delimiters.
In the split method, we can specify the string (regular expression) that acts as a delimiters and it
returns a set of
extracted strings as an array of string.
See the following example:
public class Split1
{
public static void main(String[] args)
{
String line = "www/asu/edu";
String[] words = new String[3];
//extract sub-strings using "/" as a delimiter, then the split methods returns an array of
string.
words = line.split("/");
System.out.println("size " + words.length);
for (int i=0; i<words.length; i++)
System.out.println(words[i] + " with length" + words[i].length());
//Here use are using the sting "www/asu/", thus there is no string to extract after the last "/"
//An array containing two strings will be returned.
line = "www/asu/";
words = line.split("/");
System.out.println("\nsize " + words.length);
for (int i=0; i<words.length; i++)
System.out.println(words[i] + " with length" + words[i].length());
//Here use are using the sting "www//asu", thus there is no string to extract between two "/"s
//An array containing three strings will be returned. The second string contains "" with
length 0.
line = "www//edu";
words = line.split("/");
Split method of the String class
System.out.println("\nsize " + words.length);
for (int i=0; i<words.length; i++)
System.out.println(words[i] + " with length" + words[i].length());
}
}
The out put of this program is:
size 3
www with length3
asu with length3
edu with length3
size 2
www with length3
asu with length3
size 3
www with length3
with length0
edu with length3
Note the second example with the string "www/asu/" can be modified as follows using the
second parameter of the split method.
This foces the split method to return an array cotaining 3 strings instead of 2 strings, and the last
string is "" with length 0.
line = "www/asu/";
words = line.split("/", 3);
System.out.println("\nsize " + words.length);
for (int i=0; i<words.length; i++)
System.out.println(words[i] + " with length" + words[i].length());
Powered by TCPDF (www.tcpdf.org)
Students also viewed