split() method: split method break the string into substrings based on the given regular expression.
Syntax:
public String split(String regex)
and
public String split(String regex, int limit)
Explanation:
regex: regular expression applied on string.
limit: limit for the no. of string in array. It is result threshold.
Following are the Java example codes to demonstrate working of split().
Example 1:
package JavaPkg;
public class SplitMethod {
public static void main(String[] args) {
String str = "java is a simple language";
String[] word = str.split("\\s"); //break string base on whitespace
for (String w : word) {
System.out.println(w);
}
}
}
Output:
java
is
a
simple
language
Example 2:
package JavaPkg;
public class SplitMethod2 {
public static void main(String[] args) {
String str="Java/is/a/simple/lanuage";
String[] word=str.split("/"); //split based on regular expression
for(String splitstr: word){
System.out.println(splitstr);
}
}
}
Output:
Java
is
a
simple
lanuage
Example 3:
package JavaPkg;
public class SplitMethod3 {
public static void main(String[] args) {
String str = "Java is a simple language";
String[] word = str.split("\\s", 3);
for (String splitstr : word) {
System.out.println(splitstr);
}
}
}
Output:
Java
is
a simple language
toCharArray() method in String
Syntax:
public String split(String regex)
and
public String split(String regex, int limit)
Explanation:
regex: regular expression applied on string.
limit: limit for the no. of string in array. It is result threshold.
Following are the Java example codes to demonstrate working of split().
Example 1:
package JavaPkg;
public class SplitMethod {
public static void main(String[] args) {
String str = "java is a simple language";
String[] word = str.split("\\s"); //break string base on whitespace
for (String w : word) {
System.out.println(w);
}
}
}
Output:
java
is
a
simple
language
Example 2:
package JavaPkg;
public class SplitMethod2 {
public static void main(String[] args) {
String str="Java/is/a/simple/lanuage";
String[] word=str.split("/"); //split based on regular expression
for(String splitstr: word){
System.out.println(splitstr);
}
}
}
Output:
Java
is
a
simple
lanuage
Example 3:
package JavaPkg;
public class SplitMethod3 {
public static void main(String[] args) {
String str = "Java is a simple language";
String[] word = str.split("\\s", 3);
for (String splitstr : word) {
System.out.println(splitstr);
}
}
}
Output:
Java
is
a simple language
toCharArray() method in String
No comments:
Post a Comment