How to split String into Array [Practical Examples]


Java Examples

Getting started with Split String into Array Examples

In many real time applications, we may need to work on the words of the string rather than the whole strings. In this case, we will need to split the string into its equivalent words. Java provides the split() function in a string class that helps in splitting the string into an array of string values. There are variety of ways in which we can use the split function depending on our requirement.

 

Syntax

The split function is used in two different variants as shown below.

split(String regex)
String[]	split(String regex, int limit)

The first one is used to splits this string around matches of the given regular expression. Whereas, in the second variant an additional parameter limit specifies the number of times the regex will be used as a splitting character. Here, regex parameter is a delimiter used to split the words.

 

Examples to split String into Array

Example 1 : Split String into Array with given delimiter

In this example, we are simply splitting the string using the space as a delimiter. However, we are not limiting to the number of times delimiter is used. Therefore, it will split whole string into an Array of strings.

// Program to split String into array using space delimiter
public class Main {
    public static void main(String[] args) {
        // Declaring and Initializing the variables
        String s = "Welcome to the world of java programming ";

        // Using split function 
        String[] a = s.split(" ");

        // Printing the resultant array
        for (String i: a)
            System.out.println(i);
    }
}

Output

Welcome
to 
the
world 
of
java
programming

 

Example 2 : Split String into Array with delimiter and limit

In this example, we are simply splitting the string using the space as a delimiter. Moreover, we are adding the limit as 3. Therefore, it will split the string using the space delimiter for 2 times.

// Program to split String into array using space delimiter and limit
public class Main
{
    public static void main(String[] args) {
       // Declaring and Initializing the variables
      String s="Welcome to the world of java programming ";
      
	  // Using the split function
	  String[] a = s.split(" ",3);
 
	  // Printing the resultant array
	  for (String i : a)
            System.out.println(i);      
    }
}

Outut

Welcome
to
the world of java programming

 

Example 3 : Split String into Array with another string as a delimiter

In this example, we are splitting the string using the another string as a delimiter. However, we are not adding any limit.

// Program to split String into array using other string as a delimiter
public class Main {
    public static void main(String[] args) {
        // Declaring and Initializing the variables
        String s = "Life is a book. Life is a Journey. Life is a Rose Garden.";
        String d = "Life is a ";

        // Using the split function
        String[] a = s.split(d);

        // Printing the resultant array
        for (String i: a)
            System.out.println(i);

    }
}

Output

book. 
Journey. 
Rose Garden.

 

Example 4 : Split String into Array with multiple delimiters

In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.

// Program to split String into array using multiple delimiters
public class Main {
    public static void main(String[] args) {
        // Declaring and Initializing the variables
        String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?";

        // Using split function
        String[] a = s.split("[.,!?]");
        // Printing the resultant array
        for (String i: a)
            System.out.println(i);

    }
}

Output

Life is a book
 Life is a Journey
 Is life is a Rose Garden

 

Example 5 : Split the String without using built-in split function

In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.

// Program to split String into array without using built-in split function
public class Main {
    public static void main(String[] args) {
        // Declaring and Initializing the variables
        String s = "Welcome to the world of java programming ";
        String[] a = new String[8];
        int j = 0;
        a[0] = "";

        // Iterating over string character by character
        for (int i = 0; i < s.length(); i++) {
            // If char is a space we increment the array index by 1 and store the next value as a next word
            if (s.charAt(i) == ' ') {
                j++;
                a[j] = "";
            } else {
                a[j] = a[j] + s.charAt(i);
            }
        }

        // Printing the resultant array
        for (String i: a)
            System.out.println(i);
    }
}

Output

Welcome
to
the
world
of
java
programming

 

Example 6 : Split the content read from the file line wise

In this example, we are splitting the content of file line wise. So, the delimiter is a new line character(\n). Therefore, if any of the delimiting character is found, it will split the string and store it in an array.

The content of the text file is as shown below.

Test.txt
Welcome to the world of Java Programming
Its fun to learn Programming
Have a good day!!
import java.io.*;
public class Main {
    public static void main(String[] args) throws Exception {
        // Creating a file handle and bufferedreader object
        File file = new File("Test.txt");

        BufferedReader br = new BufferedReader(new FileReader(file));

        String st, fs = "";

        // Reading from the file	   
        while ((st = br.readLine()) != null)
            fs = fs + st + "\n";

        // Spliting into an array and printing
        String[] a = fs.split("\n");
        for (String i: a)
            System.out.println(i);

    }
}

 

Example 7 : Count the number of words in a string using split method

In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.

// Program to split String into array using multiple delimiters
public class Main {
    public static void main(String[] args) {
        // Declaring and Initializing the variables
        String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?";

        // Using split function
        String[] a = s.split(" ");
        // Printing the resultant array
        for (String i: a)
            System.out.println(i);
        System.out.println("Total number of words in a string is " + a.length);

    }
}

Output

Life
is
a
book.
Life
is
a
Journey!
Is
life
is
a
Rose
Garden?
Total number of words in a string is 14

 

Summary

The knowledge of Splitting a string to an array in Java is very useful while working on real time applications. In this tutorial, we covered the way to split string into array using the built-in split function and without using split function. As per the requirement of an application, we can choose an appropriate approach for splitting. We learned in detail about splitting with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on splitting a string to an array in Java.

 

References

String Class

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment