Groovy - String split() method
split() method splits this string around matches of the given regular expression.
Syntax
String[] split(String regex)
Parameters
regex − the delimiting regular expression.
Return Value
It returns the array of strings computed by splitting this string around matches of the given regular expression.
Example - Use of split() method on String objects
Following is an example of the usage of split() method.
Example.groovy
class Example {
static void main(String[] args) {
String a = "Hello-World";
String[] str;
str = a.split('-');
for( String values : str )
println(values);
}
}
Output
When we run the above program, we will get the following result −
Hello World
Example - Splitting a String based on delimiter patterns
Following is an example of the usage of split() method.
Example.groovy
class Example {
static void main(String[] args) {
String str = "a d, m, i.n";
String delimiters = "\\s+|,\\s*|\\.\\s*";
// analyzing the string
String[] tokensVal = str.split(delimiters);
// prints the number of tokens
System.out.println("Count of tokens = " + tokensVal.length);
for(String token : tokensVal) {
System.out.print(token);
}
}
}
Output
When we run the above program, we will get the following result −
Count of tokens = 5 admin
Example - Splitting a String based on delimiter String
Following is an example of the usage of split() method.
Example.groovy
class Example {
static void main(String[] args) {
String s = "WelcomeLaughtoLaughtutorialsPoint";
String[] splitting = s.split("Laugh");
for (String splt : splitting) {
System.out.println(splt);
}
}
}
Output
When we run the above program, we will get the following result −
Welcome to tutorialsPoint
groovy_strings.htm
Advertisements