Split a String in Java

Introduction

Splitting a String in Java is a very common operation, we will discuss different method available in Java to split a String.

1. String#split() Method

Java String class provide a convenient and easy split() method to split String a String.The split method comes in 2 flavours and takes a regular expression as an input. Split method is powerful and mostly sufficient for most use cases.

If you want to limit the number of resulting parts, you can pass the second argument (limit) to the split method.The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. Here is an another variation of the above example

In case you are not passing any delimiter to above method, whitespace will be taken as a default delimiter by it.

Conclusion

In this post, we saw different methods to split a string in Java including methods available in Apache’s StringUtils class. I believe that for most of the case split() method provided by the String class will serve our purpose.

All the code of this article is available Over on Github. This is a Maven-based project.