Parsing strings using split


Terminology

General template for using split

  • parsing

  • token

  • delimiter
String line = string_to_parse;
String delims = "[delimiters]+";
String[] tokens = line.split(delims);

(use + to treat consecutive delims as one;
omit it to treat consecutive delims separately)

Example 1

String input = "23x239 u12x120:x23=5203 28340:23\n238";
String delims = "[:x]+";
String[] tokens = input.split(delims);

for (int i = 0; i < tokens.length; i++)
	System.out.println(i + ") " + tokens[i]);

What is printed out?

 

 

 

 

 

 

 


Example 2

Suppose a weather observation station has collected weather information for this year in a text file data.txt in which each line has the format

day time temperature where

For example, the first few lines of the file might look like:

1   04:45:53  -13.3 
23  14:01:17    7.5
63  11:32:28   23.8
126 13:45:37   71.5 

Complete the fileVerifier method that takes the name of a file as input and returns true only if every line in the file has the appropriate format (including appropriate ranges for the values). For each line with an invalid format, a descriptive error message should be printed.

public static boolean fileVerifier(String fileName) {