How to split a string in java

To convert a string into an array or a list, Java has a simple method on the String object: split(String regex). An application could, for example, processing a line of a simple CSV file.

This method returns an array of all sub-strings found for a given separation pattern. In the example, a list of “names”, each separated by a comma, is read into an array. In this case, the separator is the comma “,”:

public class SplitStr 
     public static void main(String []args)
        String names = "Thomas, Jean, Alex";
        String[] arr = names.split(",");
        System.out.println(arr[0]);  //Thomas
        System.out.println(arr[1]);  //Jean
        System.out.println(arr[2]);  //Alex


The problem here, is that the space before “Jean” and “Alex” remains. The variable “arr” now contains the values “Thomas”, ” Jean” and “Alex”.

To prevent this, we can also specify a regex pattern instead of the single separator In this case “comma and optionally all preceding and following spaces”:

String[] arr = names.split("\\s*,\\s*");


Split a string with Google Guava

The Google Guava library offers a very elegant way of separating a string. It offers a “fluent interface” with which various features can be added:

String names = "Thomas, Jean, Alex";

List<String> nameList = Splitter.on(",")

In the above example, the separator string is first defined with on(“,”). The method trimResults() determines that all whitespace characters before and after the elements are deleted and omitEmptyStrings() determines that empty elements are not considered. The method splitToList() concludes the statement and creates a list with the elements.
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More

Leave a Reply

Your email address will not be published. Required fields are marked *