How to Perform String to String Array Conversion in Java
Asad Riaz
Feb 02, 2024
-
split()
Method to Perform String to String Array Conversion in Java -
String[]
to Convert String to String Arrays in Java -
regex
Approach to Convert String to String Arrays in Java -
toArray()
Method for List String to String Array Conversion in Java
In Java, We could use multiple methods to perform string to string array conversion.
split()
Method to Perform String to String Array Conversion in Java
The first method is the split()
method of Java string. This method takes the string array as input and converts each entity as an individual string as output.
Example Codes:
import java.text.*;
import java.util.Date;
public class SimpleTesting {
public static void main(String args[]) {
String[] stringArray = "STRING TO STRING CONVERSION".split(" ");
for (int j = 0; j < stringArray.length; j++) {
System.out.println(stringArray[j]);
}
}
}
Output:
STRING
TO
STRING
ARRAY
CONVERSION
String[]
to Convert String to String Arrays in Java
Another approach to achieve this conversion is by using simply string index []
.
Example Codes:
import java.util.Arrays;
public class SimpleTesting {
public static void main(String[] args) {
String stringArray = "converted string";
String[] ab = new String[] {stringArray};
System.out.println(Arrays.toString(ab));
}
}
Output:
[converted string]
regex
Approach to Convert String to String Arrays in Java
Another approach to achieve this conversion is to use regex.
Example Codes:
import java.util.Arrays;
public class SimpleTesting {
public static void main(String[] args) {
String stringArray = "converted string";
String[] ab = stringArray.split("(?!^)");
System.out.println(Arrays.toString(ab));
}
}
Output:
[c, o, n, v, e, r, t, e, d, , s, t, r, i, n, g]
toArray()
Method for List String to String Array Conversion in Java
The last method is to use toArray()
method for list of strings to string array conversion. It inputs list in a single string and converts each individual into string array.
Example Codes:
import java.util.ArrayList;
import java.util.List;
public class SimpleTesting {
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("Hello");
list.add("Simple");
list.add("Testing");
String[] newStringArray = new String[list.size()];
list.toArray(newStringArray);
System.out.println("String into String Array: ");
for (int j = 0; j < newStringArray.length; j++) {
System.out.println(newStringArray[j]);
}
}
}
Output:
String into String Array:
Hello
Simple
Testing