I probably searched the internet a lot to know how to convert an array to string but wasn’t satisfied with the solution. So, I decided to come up with my own program that converts an Array to String. Still I have one problem with it but we will discuss it in the end.
First of all we declare a variable of integer data type and ask the user to enter the array to be converted to a string .Off course you are free to enter letters, numbers or symbols even though the variable is an integer type. To read the input we create a new Reader, InputStreamReader, as it reads bytes and decodes them into characters using a specified charset, and use a ‘while loop’. Now why use integer? So that the read() method reads a single character one at a time. To specify when our input stream ends we use the condition ‘not equal to’ with the help of while loop. Here to terminate the stream, I am going with whitespace but you can try anything.
Now here comes the main part of this program. To actually convert our input Array into string we use the predefined function in Java which does this for us, Character.toString(ch)
Thus our program converts each character of the array to string. You can also display the ASCII values of the data to check if the program works or not. Here is the part form while loop:
while((r=reader.read())!=’ ‘){
char ch=(char) r;
//System.out.println("The ASCI value "+r);
System.out.println(Character.toString(ch));}
Now the real problem with this program is that it converts the given array input in to string, one by one or letter by letter (if you say so) and not the complete input as a whole. If someone figures out how to do this then please let me know by commenting below or send me an email: shirishkadam35@yahoo.com and then we can accordingly update this program making it even better!
Output Window:
- Download the source code of this complete program here.
Check out my other post on How to convert a String to an Array.
Leave a Comment: