Open In App

How to Convert String to Char Stream in Java without Using Library Functions?

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 program to convert string to charStream
  
// Driver Class
public class MyClass {
      // Main Function
    public static void main(String[] args) {
          
        // storing string
        String stringData = "Hello World";
  
        // printing original string
        System.out.println("Stirng Data : "+stringData);
          
        // creating a character stream
        char[] streamChar = new char[stringData.length()];
          
        // iterating streamChar with stringData
           // to store the characters from stringData to streamChar
        for (int n = 0; n < stringData.length(); n++) {
            streamChar[n] = stringData.charAt(n);
        }
  
        // displaying the converted char Stream
        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:


Article Tags :