The String class contains a split() function. This means that any single string may be split into several substrings, based upon a nominated delimiter character. split() returns an array of String, containing each substring.
Example 1: split a string using a space as the delimiter:
Output:
Example 2: split a string using a comma (,) as the delimiter:
In the next example, we will nominate a character to use as a delineation token - the semi-colon (;).
Below is the text file shoppinglist2.txt. Note that each line contains a semi-colon. Now, rather than defaulting to whitespace as the delineation token, the Scanner will look for the semi-colon character.
Here's the code:
Note that the Scanner's property useDelimiter has been set to use the semi-colon (;). Each token is now measured by the presence of a semi-colon.