Given a String, the task is to convert the string into an Array of Strings in Java. It is illustrated in the below illustration which is as follows:
Illustration:
Input: String : "Geeks for Geeks" Output: String[]: [Geeks for Geeks]
Input: String : "A computer science portal" Output: String[] : [A computer science portal]
Methods:
They are as follows:
- Using str.split() method
- Using loops
- Using Set.toArray() method
- Using String tokenizer
- Using pattern.split() method
Lets us now discuss every method in depth implementing the same to get a better understanding of the same. They are as follows:Â
Method 1: Using str.split() methodÂ
Approach:
- Create an array with string type.
- Split the given string using string_name.split().
- Store splitted array into string array.
- Print the above string array.
Example
Java
// Java Program to Convert String to String Array// Using str.split() methodÂ
// Importing input output classesimport java.io.*;Â
// Main classpublic class GFG {    // Main driver method    public static void main(String[] args)    {        // Input string to be convert to string array        String str = "Geeks for Geeks";Â
        String strArray[] = str.split(" ");Â
        System.out.println("String : " + str);        System.out.println("String array : [ ");Â
        // Iterating over the string        for (int i = 0; i < strArray.length; i++) {            // Printing the elements of String array            System.out.print(strArray[i] + ", ");        }Â
        System.out.print("]");    }} |
String : Geeks for Geeks String array : [ Geeks, for, Geeks, ]
Method 2: Using loopsÂ
Approach:Â
- Get the set of strings.
- Create an empty string array
- Use advanced for loop, copy each element of set to the string array
- Print the string array.
Example:
Java
// Java Program to Convert String to String Array// Using HashSet and Set classesÂ
// Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set;Â
// Main classclass GFG {    // Method 1    // To convert Set<String> to String[]    public static String[] method(Set<String> string)    {        // Create String[] of size of setOfString        String[] string_array = new String[string.size()];Â
        // Copy elements from set to string array        // using advanced for loopÂ
        int index = 0;Â
        for (String str : string) {            string_array[index++] = str;        }Â
        // Return the formed String[]        return string_array;    }Â
    // Method 2    // Main driver method    public static void main(String[] args)    {        // Custom input string        String str = "Geeks for Geeks";Â
        // Getting the Set of String        Set<String> string_set            = new HashSet<>(Arrays.asList(str));Â
        // Printing the setOfString        System.out.println("String: " + str);Â
        // Converting Set to String array        String[] String_array = method(string_set);Â
        // Lastly printing the arrayOfString        // using Arrays.toString() method        System.out.println("Array of String: "                           + Arrays.toString(String_array));    }} |
String: Geeks for Geeks Array of String: [Geeks for Geeks]
Method 3: Using Set.toArray() method
Approach:
- Convert the given string into set of string.
- Now create an empty string array.
- Convert the string set to Array of string using set.toArray() by passing an empty array of type string.
- Print the array of string.
Example:
Java
// Java Program to Convert String to String Array// Using Set.toArray() methodÂ
// Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set;Â
// Main classpublic class GFG {Â
    // Method 1    // To convert Set<String> to string array    public static String[] convert(Set<String> setOfString)    {Â
        // Create String[] from setOfString        String[] arrayOfString            = setOfString.toArray(new String[0]);Â
        // return the formed String[]        return arrayOfString;    }Â
    // Method 2    // Main driver method    public static void main(String[] args)    {Â
        // Custom input string as input        String str = "Geeks for Geeks";Â
        // Getting the Set of String        Set<String> string            = new HashSet<>(Arrays.asList(str));Â
        // Printing the setOfString        System.out.println("String: " + str);Â
        // Converting Set to String array        String[] string_array = convert(string);Â
        // Print the arrayOfString        // using Arrays.toString() method        System.out.println("String array : "                           + Arrays.toString(string_array));    }} |
String: Geeks for Geeks String array : [Geeks for Geeks]
Method 4: Using String tokenizer
String tokenizer helps to split a string object into smaller and smaller parts. These smaller parts are known as tokens.
- Tokenize the given string
- Create an array of type string with the size of token counts.
- Store these tokens into a string array.
- Print the string array.
Example:
Java
// Java Program to Convert String to String Array// Using Set.toArray() methodÂ
// Importing required classes from respective packagesimport java.io.*;import java.util.StringTokenizer;Â
// Main classpublic class GFG {Â
    // Main driver method    public static void main(String[] args)    {        // Declaring and initializing integer variable        // to zero        int i = 0;Â
        // Custom input string as input        String str = "Geeks for Geeks";Â
        // Tokenize a given string using the default        // delimiter        StringTokenizer str_tokenizer            = new StringTokenizer(str);Â
        String[] string_array            = new String[str_tokenizer.countTokens()];        // Add tokens to our arrayÂ
        while (str_tokenizer.hasMoreTokens()) {            string_array[i] = str_tokenizer.nextToken();            i++;        }Â
        // Print and display the string        System.out.print("String :" + str);Â
        // Display message        System.out.print("\nString array : [ ");Â
        // Printing the string array        // using for each loop        for (String string : string_array) {            System.out.print(string + " ");        }Â
        System.out.print("]");    }} |
String :Geeks for Geeks String array : [ Geeks for Geeks ]
Method 5: Using pattern.split() method
The purpose of this pattern.split() method is to break the given string into an array according to a given pattern. We can split our string by giving some specific pattern.Â
Approach:
- Define pattern (REGEX)
- Then create a pattern using the compilation method
- Then split the string using pattern.split() with a specific pattern and store it in the array.
- Print the string array
Example:
Java
// Java Program to Convert String to String Array// Using Set.toArray() methodÂ
// Importing required classes from respective packagesimport java.io.*;import java.util.regex.Pattern;Â
// Main classpublic class GFG {    // Main driver method    public static void main(String[] args)    {        // Custom string as input        String str = "Geeks for Geeks";Â
        // Step 1: Define REGEX        String my_pattern = "\\s";Â
        // Step 2: Create a pattern using compile method        Pattern pattern = Pattern.compile(my_pattern);Â
        // Step 3: Create an array of strings using the        // pattern we already defined        String[] string_array = pattern.split(str);Â
        // Print and display string and        // its corresponding string array        System.out.print("String : " + str);        System.out.print("\nString array : [ ");Â
        // Iterating over the string        for (int i = 0; i < string_array.length; i++) {            // Printing the string array            System.out.print(string_array[i] + " ");        }Â
        System.out.print("]");    }} |
String : Geeks for Geeks String array : [ Geeks for Geeks ]
