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:

  1. 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();
  1. 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(",");
  1. 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();
}
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds