How can I split string Java efficiently using a delimiter? For example, I want to split "004-034556"
into two separate strings based on the "-"
delimiter:
part1 = "004";
part2 = "034556";
The first string should contain the characters before "-"
, and the second string should contain the characters after it. Additionally, I want to check if the string contains the delimiter before performing the split.
The most straightforward way? Just use split()
. It’s simple and gets the job done.
public class StringSplitExample {
public static void main(String[] args) {
String str = "004-034556";
if (str.contains("-")) { // Check if the delimiter exists
String[] parts = str.split("-");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Part 1: " + part1);
System.out.println("Part 2: " + part2);
} else {
System.out.println("Delimiter not found.");
}
}
}
This method works great for basic cases, but it does create an extra array, which might not be ideal for performance-sensitive scenarios.
But for those who like the old-school way, there’s also StringTokenizer
. It’s not as common now, but still handy in some cases, especially if you need to iterate through multiple tokens.
import java.util.StringTokenizer;
public class StringSplitExample {
public static void main(String[] args) {
String str = "004-034556";
if (str.contains("-")) { // Check if delimiter exists
StringTokenizer tokenizer = new StringTokenizer(str, "-");
String part1 = tokenizer.nextToken();
String part2 = tokenizer.nextToken();
System.out.println("Part 1: " + part1);
System.out.println("Part 2: " + part2);
} else {
System.out.println("Delimiter not found.");
}
}
}
It’s a bit old-fashioned since StringTokenizer
has been discouraged in favor of split()
or Scanner
, but it still works fine if you need something lightweight.