string to char array java

11/13/2022
All Articles

#string to char array java #string array #java Program #char array to string java

string to char array java

Write a Program  that convert string to char array java .

Here in this example we providing a String to our program ,  With the help of loop we spliting a input Array in the from  of character .
Function Name  -  str.charAt(i);
 
The Java String class charAt () method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string .
 
 
 
// Importing  classes
import java.util.*;
 
// writing Class
public class StringToArray{
 
// Main driver method
public static void main(String args[])
{
 
     // providing Custom input string
     String str = "DeveloperIndian";
 
      // Creating array of string length
      // using length() method
      char[] ch = new char[str.length()];
 
      // Copying character by character into array
       // using for each loop
      for (int i = 0; i < str.length(); i++)
         {
      ch[i] = str.charAt(i);
           }
 
     // show the elements of array
      // using for each loop
      for (char c : ch) {
      System.out.println(c);
                          }
}
}
 
The output of below our code are :
 
String To Array character in java , string to char array java
 
 

Another way to convert String to Array of Character in Java , we are using toCharArray()  function for spliting string .

This is simple way to perform operation and convert string to array.
Function Name  -  str.toCharArray() 
 
The java string toCharArray () method converts this string into character array.
It returns a newly created character of array,
its length is same  to this string . 
 
// Java Program to Convert a String to Character Array
 
import java.util.*;
 
// creating a Class
public class StringToArray {
 
// Main driver method
public static void main(String args[])
{
    // Custom input string
    String str = "DeveloperIndian";
 
    // Creating array and storing the array
    // returned by toCharArray() method
    char[] ch = str.toCharArray();
 
    // display  the array elements
     for (char c : ch) {
 
     System.out.println(c);
        }
}
}
 
The output of below our code are :

string to char array java , toCharArray() function definition

Article