split() and regular expression in Java

split() is a method of the String class that is used to split a string into an array of substrings based on a specified delimiter. The delimiter can be any character or sequence of characters.

Here is an example of how to use split():

String s = "Hello,World,!";
String[] words = s.split(",");

for (String word : words) {
  System.out.println(word);
}

// Output:
// Hello
// World
// !

split() can also be used with a regular expression as the delimiter. A regular expression is a pattern that can be used to match characters in a string. Regular expressions are powerful tools for matching and manipulating strings, and they are widely used in programming languages.

Here is an example of how to use split() with a regular expression:

String s = "Hello   World  !";
String[] words = s.split("\\s+");  // split on one or more whitespace characters

for (String word : words) {
  System.out.println(word);
}

// Output:
// Hello
// World
// !

In this example, the regular expression \\s+ is used to split the string on one or more whitespace characters. The \\s part of the expression matches any whitespace character (such as a space or a tab), and the + part of the expression indicates that one or more of these characters can be matched.

It's worth noting that split() is just one of the many methods in Java that can be used with regular expressions. There are also other methods available, such as matches(), replaceAll(), and replaceFirst(), which can be used to match, replace, or manipulate strings using regular expressions.