he String.split()
method in Java is used to split a string into an array of substrings based on a specified delimiter (or regular expression). It is part of the java.lang.String
class.
Syntax:
regex
: A regular expression that defines the delimiter.limit
(optional): The number of substrings to return. If the limit is:- Greater than 0: Splits the string into at most
limit
parts. - Equal to 0: Splits the string and removes trailing empty strings.
- Less than 0: Splits the string with no limit on the number of parts.
- Greater than 0: Splits the string into at most
Examples of split()
Method
1. Basic Splitting Using a Space
Output:
2. Splitting Using a Comma
Output:
3. Using a Regular Expression
Output:
4. Limiting the Number of Splits
Output:
5. Removing Trailing Empty Strings
Output:
Key Points to Remember
- The
split()
method uses regular expressions for the delimiter, so characters like.
or|
must be escaped (\\.
,\\|
). - An empty string as a delimiter will result in splitting the string into individual characters.
- Using
limit
can control how the string is divided, making it flexible for various use cases.
The split()
method is a powerful tool for parsing and processing strings in Java.