Java Program to Convert String to String Array
Last Updated :
19 May, 2022
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 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("]");
}
}
OutputString : 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));
}
}
OutputString: 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));
}
}
OutputString: 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 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("]");
}
}
OutputString :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 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("]");
}
}
OutputString : Geeks for Geeks
String array : [ Geeks for Geeks ]
Similar Reads
Java Program to Convert String to Integer Array
In Java, we cannot directly perform numeric operations on a String representing numbers. To handle numeric values, we first need to convert the string into an integer array. In this article, we will discuss different methods for converting a numeric string to an integer array in Java.Example:Below i
3 min read
Program to convert Array to Set in Java
Array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In cas
7 min read
Java Program to Convert Boolean to String
In Java programming, you might come across the need to convert a simple "true" or "false" boolean value into a String. It may seem like a challenging task, but fear not! In this article, You will explore some methods to convert a boolean value to a string in Java Method for Boolean to String Convers
4 min read
Java Program to Convert String to String Array Using Regular Expression
Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided un
3 min read
Program to Convert Stream to an Array in Java
A Stream is a sequence of objects that support various methods which can be pipelined to produce the desired result. An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition
3 min read
Java Program to Convert Long to String
The long to String conversion in Java generally comes in need when we have to display a long number in a GUI application because everything is displayed in string form. In this article, we will learn about Java Programs to convert long to String. Given a Long number, the task is to convert it into a
4 min read
Java Program to Convert String to Object
In-built Object class is the parent class of all the classes i.e each class is internally a child class of the Object class. So we can directly assign a string to an object. Basically, there are two methods to convert String to Object. Below is the conversion of string to object using both of the me
2 min read
Program to convert Boxed Array to Stream in Java
An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In case of primitives data types, the actual values are stored in contiguous memory locations. In case
3 min read
Java Program to Convert a Float value to String
Given a Float value in Java, the task is to write a Java program to convert this float value to string type. Examples: Input: 1.0 Output: "1.0" Input: 3.14 Output: "3.14" Strings - Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are
4 min read
Java Program to Read a File to String
There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file. Given a text file, the task is to read the contents
8 min read