In this section, you will learn how to split string into different parts using spit() function.
In the given below example, the first string splits where the compiler finds the delimiter '-' and second string splits where it finds the delimiter '.' . The third string splits where it finds the '.' delimiter but it will split it into only 3 parts in spite of 4 parts because we define it in the function split() that split the string into 3 parts. The string will split from the first three delimiter.
public class SplitString {
public static void main(String args[]) {
//Defining string and array
String sample = "Sucess-need-continous-effort";
String subStr[];
System.out.println("EXAMLES OF SPLITTING STRING");
System.out.println("");
//Defining delimiter '-' and splitting string at '-'
System.out.println("Splitting string at '-'");
String delimiter = "-";
subStr = sample.split(delimiter);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");
//Defining delimiter '.' and splitting string at '.'
System.out.println("Splitting string at '.'");
sample = "Sucess.need.continous.effort";
delimiter = "\\.";
subStr = sample.split(delimiter);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");
//Defining delimiter '.' and splitting string at '.'
System.out.println("Splitting string at '.' in three part only, regardless of delimiter");
subStr = sample.split(delimiter, 3);
for (int i = 0; i < subStr.length; i++)
System.out.println(subStr[i]);
System.out.println("");
}
}
| EXAMLES OF SPLITTING STRING Splitting string at '-' Sucess need continous effort Splitting string at '.' Sucess need continous effort Splitting string at '.' in three part only, regardless of delimiter Sucess need continous.effort |
|
Recommend the tutorial |

Ask Questions? Discuss: Java String Split Example
Post your Comment