What is the method to convert a Java string to an array?
There are several methods in Java to convert a string to an array, here are three common ones:
- By utilizing the toCharArray() method of the String class, the string can be converted into a character array.
String str = "Hello World";
char[] charArray = str.toCharArray();
- The split() method of String: This method splits a string into an array of strings based on a specified delimiter.
String str = "Hello,World";
String[] strArray = str.split(",");
- The StringTokenizer class can be used to split a string into an array of strings based on a specified delimiter.
String str = "Hello,World";
StringTokenizer tokenizer = new StringTokenizer(str, ",");
String[] strArray = new String[tokenizer.countTokens()];
int i = 0;
while (tokenizer.hasMoreTokens()) {
strArray[i++] = tokenizer.nextToken();
}