W3docs

string to string array conversion in java

There are several ways to convert a string to a string array in Java. Here are a few options:

There are several ways to convert a string to a string array in Java. Here are a few options:

  1. Using the split() method of the String class:

String input = "Hello World";
String[] words = input.split(" ");

This will split the input string on the space character and return an array of strings, where each element is a word from the input string.

  1. Using the toCharArray() method of the String class:

String input = "Hello World";
char[] chars = input.toCharArray();
String[] words = new String[chars.length];
for (int i = 0; i < chars.length; i++) {
  words[i] = Character.toString(chars[i]);
}

This will convert the input string to an array of characters, and then create a new string array where each element is a single-character string. Note that this approach does not split by words; it converts every character individually.

  1. Using the Pattern class from the java.util.regex package:

import java.util.regex.Pattern;

String input = "Hello World";
String[] words = Pattern.compile(" ").split(input);

This will use a regular expression to split the input string on the space character and return a string array where each element is a word from the input string.