How To Split A String Into Substrings in Java
Chapter:
String Handling
Last Updated:
22-08-2023 17:12:00 UTC
Program:
/* ............... START ............... */
public class StringSplitExample {
public static void main(String[] args) {
String input = "Hello,World,Java";
String[] parts = input.split(",");
for (String part : parts) {
System.out.println(part);
}
}
}
// another program for splitting
public class ComplexSplitExample {
public static void main(String[] args) {
String input = "apple orange;banana|grape";
String[] parts = input.split("[,;|]");
for (String part : parts) {
System.out.println(part);
}
}
}
/* ............... END ............... */
Notes:
-
In first example, the string "Hello,World,Java" is split using the comma , as the delimiter. The resulting array parts will contain three elements: "Hello", "World", and "Java", which are then printed using a loop.
- In second example, the regular expression [,;|] specifies that the string should be split at commas, semicolons, or pipe symbols, resulting in four substrings: "apple", "orange", "banana", and "grape".
- Keep in mind that the split() method uses regular expressions, so if your delimiter contains special characters that are also used in regular expressions, you might need to escape those characters appropriately.
Tags
How to split a string into substrings in java #Java split string by space #How to split a string into substrings in java example