Introduce Java How To Convert a String to an Array and give examples
In Java, converting a string to an array can be done in several ways, depending on what kind of array you want to create. The most common scenarios are converting a string into an array of characters or splitting a string into an array of substrings based on a delimiter.
To convert a string into an array of characters, you can use the toCharArray()
method of the String
class. This method returns a new character array containing the characters of the string.
Example:
public class StringToCharArray {
public static void main(String[] args) {
String str = "Hello, World!";
// Convert string to character array
char[] charArray = str.toCharArray();
// Print the character array
System.out.println("Character Array: ");
for (char c : charArray) {
System.out.print(c + " ");
}
}
}
Output:
Character Array:
H e l l o , W o r l d !
If you want to split a string into an array of substrings based on a specific delimiter, you can use the split()
method of the String
class. This method takes a regular expression as an argument and returns an array of strings.
Example:
public class StringToArray {
public static void main(String[] args) {
String str = "Java,Python,C++,JavaScript";
// Split the string by comma
String[] languages = str.split(",");
// Print the array of substrings
System.out.println("Array of Substrings: ");
for (String language : languages) {
System.out.println(language);
}
}
}
Output:
Array of Substrings:
Java
Python
C++
JavaScript
toCharArray()
to convert a string into a character array.split(delimiter)
to convert a string into an array of substrings based on a specified delimiter.These methods are straightforward and commonly used in Java programming for string manipulation.