THINK FIRST·CODE LATER

← All labs

A split that keeps the delimiters

Problem

"3+45*2".split(...) loses the operators. Write a utility class Splitter with a static method

public static String[] split(String text, String delimiters)

that cuts the text at every character found in delimiters and keeps each delimiter as a piece of its own: split("ab#12#453", "#") gives ab, #, 12, #, 453.

Design it top-down with two helpers: isDelimiter(char c, String delimiters) and countPieces(text, delimiters) — an array needs its size before it is filled, so the pieces are counted first. Do not use ArrayList or regular expressions.

SplitterApp reads the text on the first line and the delimiters on the second. For the input

3+45*2-7
+-*/

the program prints

Pieces: 7
1: 3
2: +
3: 45
4: *
5: 2
6: -
7: 7

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l12-8-data-1.txt

3+45*2-7
+-*/
What your program must print for l12-8-data-1.txt
Pieces: 7
1: 3
2: +
3: 45
4: *
5: 2
6: -
7: 7

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l12-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l12-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.