While programming, we may need to break a string based on some attributes. Mostly this attribute will be a separator or a common - with which you want to break or split the string.
StrSplit() method splits a String into an array of substrings given a specific delimiter.
- Regex: The regular expression is applied to the text/string
- Limit: A limit is a maximum number of values the array. If it is omitted or zero, it will return all the strings matching a regex.
Split String Example
Suppose we have a string variable named
strMain formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by the comma (,).
Here if we want all individual strings, the best possible pattern would be to split it based on the comma. So we will get five separate strings as follows:
Use the split method against the string that needs to be divided and provide the separator as an argument.
In this case, the separator is a comma (,) and the result of the split operation will give you an array split.
The loop in the code just prints each string (element of array) after the split operation, as shown below-
Example: Java String split() method with regex and length
Consider a situation, wherein you require only the first ‘n’ elements after the split operation but want the rest of the string to remain as it is. An output something like this-
- Delta, Gamma, Sigma
This can be achieved by passing another argument along with the split operation, and that will be the limit of strings required.
Consider the following code –
How to Split a String by Space
Consider a situation, wherein you want to split a string by space. Let’s consider an example here; we have a string variable named strMain formed of a few words Welcome to Java.