How to perform string to string array conversion in Java

  1. split() method to perform string to string array conversion in Java
  2. String[] to convert string to string arrays in Java
  3. regex approach to convert string to string arrays in Java
  4. 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 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
comments powered by Disqus