Using String split Method
Sometimes the data in a text file is formatted where each value is separated by a delimiter. The delimiter is simply used to separate the data. One example of a delimiter is a comma (,). If you have data that is separated by a comma, you split up the string at each comma. The comma is not included in the array of data.
String[] split(String del)
This method returns a String array where each element is a substring of this String, which has been split around matches of the given expression del.
In the example below, a space is being used as the delimeter to split the string into substrings of the individual words.
String sentence = "The big fat lazy dog";
String[] words = sentence.split (" ");
Your Turn
Let's try it in the Java Playground.
- Predict the output of the code.
- Run the code to determine if your prediction is correct.
- Instead of spaces between the words in
sentence, change them to commas. Modify the call to split to still separate the String out into the different words.
- Run the code to see if you get the same result.
Using split with Files
When you read data from a file, you can use split to separate out your data into an array. If you had a file with a line of text separated by a comma, you could separate the values into an array as follows.
File input = new File(<String for the file name of the text file>);
Scanner in = new Scanner(input);
String line = in.nextLine();
String[] individualValues = line.split(",");
Resources