How to Convert String to Char Stream in Java without Using Library Functions?
Last Updated :
12 Feb, 2024
In Java, we can convert a string to a char stream with a simple built-in method .toCharArray(). Here, we want to convert the string to a char stream without using built-in library functions. So, we will create an empty char array iterate it with string characters, and store the individual characters from the string to the char array one after the other.
In this article, we will learn how to convert String to char stream in Java without using library functions.
Example of String to char stream in Java
Input: Hello World
Output: H e l l o W o r l d
Input: She is Intelligent
Output: S h e i s I n t e l l i g e n t
Program to Convert String to Char Stream Without Using Library Functions in Java
Below is the implementation to convert string to char stream using charAt() method in Java.
Java
public class MyClass {
public static void main(String[] args) {
String stringData = "Hello World" ;
System.out.println( "Stirng Data : " +stringData);
char [] streamChar = new char [stringData.length()];
for ( int n = 0 ; n < stringData.length(); n++) {
streamChar[n] = stringData.charAt(n);
}
System.out.print( "Converted Character Stream : " );
for ( char chr : streamChar) {
System.out.print(chr + " " );
}
}
}
|
Output
Stirng Data : Hello World
Converted Character Stream : H e l l o W o r l d
Explanation of the Program:
- In the above program, we have firstly stored a string in a string variable.
- Then we have created an empty char stream with the size of string.
- After that we iterated the char stream with string data.
- By using charAt() we will be getting the individual character from string.
- Storing each character from the string into the char stream till the string size exceeds.
- Finally displaying the char stream.
Share your thoughts in the comments
Please Login to comment...