How to convert a String to an Array ?

Standard

     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.

Shirishkadam-sta

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.

shirishspaces-sta

  • To download the complete program click here:

Download String to Array project

To convert an Array to String checkout his program I made recently How to Convert an Array to a String.

Advertisements

One thought on “How to convert a String to an Array ?

Leave a Comment:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s