Java Program To Split A String
Chapter:
String Handling
Last Updated:
03-06-2023 12:42:54 UTC
Program:
/* ............... START ............... */
public class StringSplitExample {
public static void main(String[] args) {
String str = "Hello,World,Java,Program";
String delimiter = ",";
// Splitting the string
String[] parts = str.split(delimiter);
// Printing the split parts
for (String part : parts) {
System.out.println(part);
}
}
}
/* ............... END ............... */
Output
Notes:
-
We start by defining a string str that contains the text we want to split. In this example, the string is "Hello,World,Java,Program".Next, we define a variable called delimiter and assign it the value of ",". This is the character that we'll use as the delimiter to split the string. In this case, we're using a comma as the delimiter.
- Now, we use the split() method of the String class to split the string str into an array of substrings. The split() method takes the delimiter as an argument and returns an array of substrings.
- We store the resulting substrings in an array called parts. Each element of the array will correspond to a part of the original string that was separated by the delimiter.Finally, we iterate over the parts array using a for-each loop and print each part on a new line. This allows us to see the individual parts of the original string that were split using the delimiter.
Tags
Java program to split a string #How do I split a string in Java #Java String split by dot