At times, we need to convert a string in to an array in order to use it in our program so how do we do that. Below I have a JAVA program that will help you to convert any String to an Array.
First we declare a variable of String data-type. Then we ask the user to enter the string that is to be converted to Array. To read the input by the user we use Scanner. Now Java provides a predefined function to convert a data-type to Character-Array, which is toCharArray();
This function in particular converts the data provided by the user to CharArray. Later we display this converted data properly in an array format. For that we use ‘for loop’ and declare an integer initializing it to zero, which has to be strictly less than the length of our string. By using post increment we can display how each character gets stored one by one in the array.
Here is the code for it:
char a[]=s.toCharArray();
for (int i=0;i<s.length();i++){
System.out.println("Data at ["+i+"]= "+a[i]);}
Although you should be careful with whitespaces as they terminate the string and the compiler neglects whatever that comes after space when it encounters one.
- To download the complete program click here:
To convert an Array to String checkout his program I made recently How to Convert an Array to a String.
Leave a Comment: