Java Program to Convert String to String Array
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:
Input: String : "Geeks for Geeks" Output: String: [Geeks for Geeks]
Input: String : "A computer science portal" Output: String : [A computer science portal]
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
- Create an array with string type.
- Split the given string using string_name.split().
- Store spitted array into string array.
- Print the above string array.
String : Geeks for Geeks String array : [ Geeks, for, Geeks, ]
Method 2: Using loops
- 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.
String: Geeks for Geeks Array of String: [Geeks for Geeks]
Method 3: Using Set.toArray() method
- 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.
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.
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.
- 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
String : Geeks for Geeks String array : [ Geeks for Geeks ]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.