Java Splitting and Joining Text
Splitting breaks text into pieces, and joining rebuilds pieces into one line. Split takes a pattern, not just plain text.
Split breaks a line on commas
Each comma marks a cut. The pieces print as an array.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] parts = "ana,ben,cid".split(",");
System.out.println(Arrays.toString(parts));
}
}The dot trap
An unescaped dot matches every character, so no pieces survive. An escaped dot splits on real dots.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString("a.b.c".split(".")));
System.out.println(Arrays.toString("a.b.c".split("\\.")));
}
}A limit leaves the rest uncut
Limit three allows three pieces only. The last piece keeps its dots.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] parts = "a.b.c.d.e".split("\\.", 3);
System.out.println(Arrays.toString(parts));
}
}Join rebuilds one line
Join places a separator between the pieces. The pieces keep their order.
public class Main {
public static void main(String[] args) {
String line = String.join(", ", "Ana", "Ben", "Cid");
System.out.println(line);
}
}Strip and isBlank clean and judge
Strip trims both ends, and the lengths prove it. IsBlank answers true only for a spaces-only line.
public class Main {
public static void main(String[] args) {
String messy = " hello ";
System.out.println(messy.length());
System.out.println(messy.strip().length());
System.out.println(" ".isBlank());
System.out.println(" hi ".isBlank());
}
}Example
public class Main {
public static void main(String[] args) {
String line = "ana, ben, cid";
String[] parts = line.split(",");
for (int i = 0; i < parts.length; i++) {
parts[i] = parts[i].strip();
}
System.out.println(String.join(" | ", parts));
System.out.println(parts.length);
}
}Key points
- Split breaks a line on its pattern into an array of pieces.
- The dot is a pattern that matches any character, so it must be escaped to mean a real dot.
- A limit caps the pieces and leaves the rest uncut in the last piece.
- String.join rebuilds pieces into one line with a separator.
- Strip cleans spaces from both ends of a line.
- IsBlank judges whether a line holds only spaces.
In this example, a comma line splits into pieces, each piece strips its stray spaces, and join rebuilds a clean line.
Note
Strip removes ends only, so inner spaces stay in place.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Splitting a.b.c.d.e with limit 3 gives which last piece?