In this blog, we will deep dive and study about how to convert string to array in Java. In Java, strings are objects of the String class, which are nothing more than a collection of characters. Since Strings are immutable in Java, changing the value of a String results in the creation of a new String object rather than changing the value of the already-existing String object. The Java String class can be imported from the java.lang package.
An object called a Java array is made up of elements with identical data types. In addition, the elements of an array are kept in direct range to one another in memory. Java does not allow you to adjust the size of an array, so it is assumed that an array has a fixed number of elements.
We’ll go through Java’s character and string arrays in this tutorial.
This article intends to:
- Discuss the different ways to convert string to array of characters in Java.
- Describe four different ways to convert string to array of strings in Java.
- Using the String.split() function
- Pattern.split() method use
- Applying the toArray() function
- Using the String[] method
In Java, a string is an object that represents a group of characters. Because Java Strings are immutable, their value cannot be modified after they are formed.
A straightforward for loop or the toCharArray() method can be used to convert a String to a char array.
In Java, a string array is a collection of strings. Java arrays have a defined length. Any of the following methods, such as String.split(), Pattern.split(), String[] {} and toArray(), can be used to transform a String to an array.
Convert String to Array of Character in Java
In Java, there are two ways to transform a String object into a character array:
1. Naive Approach To Convert String to Array Of Character
A normal for-loop is used to read every character in the string and assign each one individually to a Character array.
Algorithm:
- Get the string
- The string’s length should match the size of the character array you create.
- Traversing the string copies the character at the ith place to the ith index of the array.
- Return the array of characters or carry out the operation on it.
Code Implementation
import java.util.*; class StringtoCharArray { public static void main(String args[]) { String str = "PrepBytes"; // Given String // Creating array of string length char[] arr = new char[str.length()]; // Copy character by character into array for (int i = 0; i < str.length(); i++) { arr[i] = str.charAt(i); } // Printing the character array for (char x : arr) { System.out.println(x); } } }
Output:
P
r
e
p
B
y
t
e
s
2. Using toCharArray() Method To Convert String To Array of Character
We can employ the toCharArray() function to transform a string into a char array.
Algorithm:
- Get the string
- The character array that the toCharArray() method returns should be placed in a character array.
- Return the character array or use it to perform an action.
Code Implementation
import java.util.*; class StringtoCharArray { public static void main(String args[]) { String str = "PrepBytes"; // Call the toCharArray() method // Store the result in a char array char[] arr = str.toCharArray(); // Printing the character array for (char x : arr) { System.out.println(x); } } }
Output:
P
r
e
p
B
y
t
e
s
Convert String To Array of Strings in Java
In this section, we’ll learn how to create an array of strings from a string in Java.
There are four ways to Convert String To Array of Strings in Java:
- Using String.split() Method
- Using Pattern.split() Method
- Using String[ ] Approach
- Using toArray() Method
Using String.split() Method To Convert String To Array Of Strings
Using the given delimiter (whitespace or other symbols), the String.split() function divides a string into separate strings . These objects can be kept in a string array directly.
Example 1:Take a look at the example below, which demonstrates how to use Java’s String.split() function to transform a string to an array.
class StrintoStringArray { public static void main(String[] args) { // Declaring and initializing a string String str = "Learn Coding From PrepBytes"; // Declaring an empty string array String[] arr = null; // Converting using String.split() method with whitespace as a delimiter arr = str.split(" "); // Printing the converted string array for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
Output:
Learn
Coding
From
PrepBytes
Example 2: In the example below, we convert string to array in Java by using the # delimiter.
class StringtoStringArray { public static void main(String[] args) { // Declaring and initializing a string String str = "What#is#your#name ?"; // Declaring an empty string array String[] arr = null; // Converting using String.split() method // with hash(#) as a delimiter arr = str.split("#"); // Printing the converted string array for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
Output:
What
is
your
name ?
Using Pattern.split() Method To Convert String To Array Of Strings
The Pattern.split() method divides a string into an array of strings by using a regular expression (pattern) as the delimiter.
As seen in the code below, we must import the Pattern class into our Java code before we can apply the technique. Complex regex expressions can be compiled using this Pattern class.
Example 1: A string will be divided into an array in the example below by using whitespace as the delimiter.
import java.util.regex.Pattern; class PatternSpiltMethod { public static void main(String[] args) { // Declaring and initializing a string String str = "Pattern.split() method to convert a string to array in Java "; // Declaring an empty string array String[] arr = null; // Parsing white space as a parameter Pattern ptr = Pattern.compile(" "); // Storing the string elements in array after splitting arr = ptr.split(str); // Printing the converted string array for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
Output:
Pattern.split()
method
to
convert
a
string
to
array
in
Java
Example 2: To divide a string into an array, we may also use any string or pattern as a delimiter. Here, the &d& delimiter has been utilized.
import java.util.regex.Pattern; class PatternSpiltMethod { public static void main(String[] args) { // Declaring and initializing a string with a separator String str = "What&d&is&d&your&d&name ?"; // Declaring an empty string array String[] strArray = null; // Splitting the string with delimiter as #a1 String patternStr = "&d&"; Pattern ptr = Pattern.compile(patternStr); // Storing the string elements in array after splitting strArray = ptr.split(str); // Printing the converted string array for (int i = 0; i < strArray.length; i++) { System.out.println(strArray[i]); } } }
Output:
What
is
your
name ?
Using String[ ] Approach To Convert String To Array of Strings
By simply placing a string inside the curly brackets of String [] {}, we may transform a string to a string array. This conversion will result in the creation of a String array with just the input string as its single element.
Take a look at the example below, which demonstrates how to use Java’s String[] {} method to transform a string to an array.
import java.util.Arrays; class StringtoStringArray { public static void main(String[] args) { // Declaring and initializing a string String str = "Using the String[] method to convert a string to array in Java"; // Passing the string to String[] {} String[] arr = new String[] {str}; // Printing the elements of the string array using a for loop for(String ch : arr) { System.out.println(ch); } } }
Output
Using the String[] method to convert a string to array in Java
Using toArray() Method To Convert String To Array Of Strings
Java programmers can also convert a string to an array by using the toArray() method of the List class. It accepts a list of String objects as input and turns each one into a string array element.
Take a look at the example below, where we turned a list of strings into a string array.
import java.util.ArrayList; import java.util.List; class ListToStringArray { public static void main(String[] args) { // Creating a list of type string List<String> list = new ArrayList<String>(); // Adding elements to list list.add("What"); list.add("is"); list.add("your"); list.add("name ?"); // Size of list int list_size = list.size(); // Creating string array String[] arr = new String[list_size]; // Converting to string array list.toArray(arr); // Printing the string array for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
Output
What
is
your
name ?
Conclusion
The string in Java is essentially an object that represents a list of char values. Similar to a Java string, a character array functions similarly.
In Java, strings are immutable.
An object with elements of a similar data type is called a Java array. Java arrays have a defined length.
Either a crude for loop or the toCharArray() method can be used to convert a String to a character array.
Using the String.split() or Pattern.split() methods, we can transform a string into a string array depending on a delimeter.