Splitting Strings in Java
Using the split() method
Java provides a built-in split() method to divide a string into an array of substrings based on a specified delimiter.
Java
String str = "This is a sample string";
String[] words = str.split(" "); // Split by whitespace
for (String word : words) {
System.out.println(word);
}
Use code with caution.
Understanding the split() method
Delimiter: The split() method takes a regular expression as a delimiter.
Returns: It returns a String array containing the split substrings.
Example with a custom delimiter
Java
String str = "apple,banana,orange";
String[] fruits = str.split(","); // Split by comma
for (String fruit : fruits) {
System.out.println(fruit);
}
Use code with caution.
Handling empty strings
If the delimiter appears at the beginning or end of the string, or if there are consecutive delimiters, empty strings might be included in the resulting array. You can use the limit parameter to control this behavior.
Java
String str = ",,apple,banana,,";
String[] fruits = str.split(",", -1); // Keep empty strings
for (String fruit : fruits) {
System.out.println(fruit);
}
Use code with caution.
Key points to remember
The delimiter can be any regular expression.
The limit parameter controls the number of resulting substrings.
Be aware of potential empty strings in the result.
visit here