Open In App

Java Program to Convert String to String Array

Last Updated : 19 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Using str.split() method
  2. Using loops
  3. Using Set.toArray() method
  4. Using String tokenizer
  5. 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 classes
import java.io.*;
 
// Main class
public 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("]");
    }
}


Output

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 packages
import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
// Main class
class 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));
    }
}


Output

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 packages
import java.io.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
 
// Main class
public 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));
    }
}


Output

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.

  1. Tokenize the given string
  2. Create an array of type string with the size of token counts.
  3. Store these tokens into a string array.
  4. Print the string array.

Example:

Java




// Java Program to Convert String to String Array
// Using Set.toArray() method
 
// Importing required classes from respective packages
import java.io.*;
import java.util.StringTokenizer;
 
// Main class
public 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("]");
    }
}


Output

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:

  1. Define pattern (REGEX)
  2. Then create a pattern using the compilation method
  3. Then split the string using pattern.split() with a specific pattern and store it in the array.
  4. Print the string array

Example:

Java




// Java Program to Convert String to String Array
// Using Set.toArray() method
 
// Importing required classes from respective packages
import java.io.*;
import java.util.regex.Pattern;
 
// Main class
public 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("]");
    }
}


Output

String : Geeks for Geeks
String array : [ Geeks for Geeks ]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads