Copy characters from string into char Array in Java


Let’s say we have the following string.

String str = "Demo Text!";

To copy some part of the above string, use the getChars() method.

// copy characters from string into chArray
=str.getChars( 0, 5, chArray, 0 );

The following is an example to copy characters from string into char Array in Java.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "Demo Text!";
      char chArray[] = new char[ 5 ];
      System.out.println("String: "+str);
      // copy characters from string into chArray
      str.getChars( 0, 5, chArray, 0 );
      System.out.print("Resultant character array...
");       for (char ch : chArray)          System.out.print( ch );    } }

Output

String: Demo Text!
Resultant character array...
Demo

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements