Split a String in Java

Split a String in Java

In this small post, we will explore how to split a string in Java.

 

Introduction

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

 

1. String#split() Method

Java String class provides 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.

public void split(){
    String input = "This-is-a-sample-input";
    String[] parts= input.split("-");
    for(int i =0; i< parts.length;i++){
        System.out.println(parts[i]);
    }
}

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 it applies the pattern and therefore affects the length of the resulting array. Here is an another variation of the above example

public void splitWithLimit(){
    String input = "This-is-a-sample-input";
    String[] parts= input.split("-", 2);
    for(int i =0; i< parts.length;i++){
        System.out.println(parts[i]);
    }
}

If you run above example, output will be

This
is-a-sample-input

Please note that split() method takes a regular expression as an input and we need to escape special character if needed (Please check different special character available in regular expression ). We can use \ to escape special characters or Pattern.quote() for it.

 

2. Split String Using Java 8

With Java 8, we can use Stream and Collector to split String. Here is a simple code to split a string in Java 8

public void splitStringJava8(){
    String input = "This-is-a-sample-input";
    List<String> parts = Pattern.compile("-")
                         .splitAsStream(input)
                         .collect(Collectors.toList());
    parts.forEach(s-> System.out.println(s));
}

 

3. Split String Apache Utils

Apache StringUtils provide null safe methods to split a string, here is a sample code for the same

public void apacheStringUtils(){
    String input = "This-is-a-sample-input";
    String[] parts =StringUtils.split(input ,"-");
    for(int i =0; i< parts.length;i++){
        System.out.println(parts[i]);
    }
}

In case you are not passing any delimiter to above method, it will take white space 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 for most 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.