How to split String in java

String API provides 2 methods to split String in java.

Both these methods return a array of String that has been split.
In this post we will see some examples using both these methods.

1. Split String using split(String regex)

In the below code we have used the split in 3 different scenarios
1. Splitting String with a delimiter as ” ” (space)
2. Splitting String with a delimiter as a character (“o” in case of the example)
3. Splitting String with a delimiter as a regular expression ([abc])

Output

2. Split String using split(String regex,int limit)

For splitting a String you can also specify how much a string should be split.
split(String regex,int limit) works similar to split(String regex), but stops splitting the string once the given limit is achieved.
We will use the same example that we have discussed above, only difference : we will be adding a limit to split.

We have added 3 types of limit.
1. In 1st case we have added 4 as the limit. Here the output is – String is split in 4 parts
2. In 2nd case we have added 0 as the limit. Here the output is – String is split similar to Split(String regex)
So we should note that, if we want to split a string for desired limit, the the limit should be greater than 0.
3. In 3rd case we have added a very large limit. Here the output is – String is split similar to Split(String regex).

Output

References

1. String.split(String)

2. String.split(String,int)

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn