Splitting, joining and replacing
The methods of this lesson treat the string as a whole text: they cut it at a separator, put pieces back together, replace every match of a pattern and answer whether the whole text matches one. All of them return a new string or a new array, because the original cannot change.
split
split takes a regular expression, not a plain separator, and returns an array of the pieces. A comma is a plain character in a regex, so the common case needs no escape. A separator that matches nothing is a mistake: an empty result cannot be indexed.
The file Split.java:
import java.util.Arrays;
public class Split {
public static void main(String[] args) {
String csv = "ada,grace,alan";
String[] parts = csv.split(",");
System.out.println(Arrays.toString(parts));
System.out.println("count: " + parts.length);
String[] limited = csv.split(",", 2);
System.out.println(Arrays.toString(limited));
System.out.println(String.join(" | ", parts));
}
}
javac -Xlint:all Split.java
java Split
[ada, grace, alan]
count: 3
[ada, grace,alan]
ada | grace | alan
The separators disappear, so the pieces are the names without commas. A trailing empty piece is removed by default, which is why "a,b,".split(",") has two elements and not three.
split with a limit
The second argument is the maximum number of pieces. With 2, the first separator is used and the rest of the text stays in the last piece, which is how the key of a key=value line is separated from a value that may itself contain the character. The output above shows the second piece as grace,alan.
A negative limit keeps trailing empty pieces, so split(",", -1) on "a,b," gives three pieces, the last empty. That is the way to preserve an empty field at the end of a CSV line.
join
String.join takes a separator and either an array or an Iterable of values, and puts the separator between them without one at either end. It is the counterpart of split, and it does internally what the builder loop of the previous lesson does by hand.
replace and replaceAll
replace takes two plain strings, and replaceAll takes a regular expression and a replacement. The replacement may refer to a captured group as $1. Neither changes the original, and both return a new string even when no match was found.
public class Replace {
public static void main(String[] args) {
String text = "a-b-c";
System.out.println(text.replace("-", "+"));
System.out.println(text.replaceAll("[abc]", "x"));
System.out.println("ab".repeat(3));
System.out.println(text.toUpperCase());
System.out.println("123".matches("[0-9]+"));
System.out.println("12a".matches("[0-9]+"));
}
}
javac -Xlint:all Replace.java
java Replace
a+b+c
x-x-x
ababab
A-B-C
true
false
replaceAll("[abc]", "x") replaces each of a, b and c, not the sequence, which is the difference between a character class and a literal string. repeat is the shortest way to build a separator line, and toUpperCase shows once more that the original a-b-c is untouched.
matches
matches asks whether the whole text matches the pattern, not whether it contains a match. For a search inside the text the class is Pattern with find, which lesson 112 takes apart. The character class [0-9] is the long form of \d; both work in a Java string as long as the backslash is doubled in the source, as in "\\d+".
A quantifier follows the thing it repeats: + means one or more, * zero or more and ? zero or one. A pattern with no anchor still has to match the whole string for matches, so [0-9]+ already means all digits and no others.
A log line parsed
A split with a limit is the usual way to parse a line whose first fields are fixed and whose rest is free text. The last piece keeps its spaces, because the limit stops the splitting after the third separator.
public class Log {
public static void main(String[] args) {
String line = "2024-05-01 12:30:45 INFO user=ada action=login";
String[] parts = line.split(" ", 4);
System.out.println("date: " + parts[0]);
System.out.println("time: " + parts[1]);
System.out.println("level: " + parts[2]);
System.out.println("rest: " + parts[3]);
}
}
javac -Xlint:all Log.java
java Log
date: 2024-05-01
time: 12:30:45
level: INFO
rest: user=ada action=login
Four pieces from one line, and the fourth holds the whole message. Splitting into three would lose the message, and splitting into five would cut it at the first space of user=ada.
Exercises
- Split a,b, with no limit and with -1, and compare the lengths.
- Join the pieces of Split.java with a comma and no spaces, and compare the result with the input.
- Replace every digit in a phone number with * using replaceAll.
- Parse a line with one more field before the message and adjust the limit.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
"a,b,c".split(",")return?Answer
An array of three strings
split cuts at each separator and gives one piece per field, so three here.
-
What does the second argument of
splitmean?Answer
The maximum number of pieces
The limit stops the split after that many pieces, leaving the rest in the last one.
-
What is the difference between
replaceandreplaceAll?Answer
replace takes a literal, replaceAll takes a regex
replace treats its first argument as text, while replaceAll compiles it as a regular expression.
-
What does this program print?
import java.util.Arrays; public class Q1 { public static void main(String[] args) { String[] parts = "a-b-c".split("-"); System.out.println(Arrays.toString(parts) + " " + parts.length); } }Answer
[a, b, c] 3
Two separators give three pieces, and toString writes them in brackets.
-
What does this program print?
import java.util.Arrays; public class Q2 { public static void main(String[] args) { String[] parts = "a,b,c".split(",", 2); System.out.println(Arrays.toString(parts)); } }Answer
[a, b,c]
The limit of two pieces leaves the rest of the text in the second piece.
-
What does this program print?
public class Q3 { public static void main(String[] args) { System.out.println(String.join("-", "a", "b", "c")); } }Answer
a-b-c
The separator goes between the values and not at the ends.
-
What does this program print?
public class Q4 { public static void main(String[] args) { String text = "a1b2"; System.out.println(text.replaceAll("[0-9]", "")); } }Answer
ab
The class matches each digit, and the empty replacement removes it.
-
What does this program print?
public class Q5 { public static void main(String[] args) { System.out.println("abc".matches("a.c") + " " + "abc".matches("b")); } }Answer
true false
The dot matches one character, so a.c matches abc, while b does not match the whole string.
-
What does
"ab".repeat(3)return?Answer
ababab
repeat concatenates the string with itself the given number of times.
-
What does this program print?
public class Q6 { public static void main(String[] args) { String line = "INFO user=ada action=login"; String[] parts = line.split(" ", 2); System.out.println(parts[0] + " / " + parts[1]); } }Answer
INFO / user=ada action=login
The limit of two keeps everything after the first space in the second piece.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev