Extracting a substring as an array of characters in Java


To extract a substring as an array of characters in Java, use the getChars() method.

Let’s say the following is our string and character array.

String str = "World is not enough!";
char[] chArr = new char[10];

Now, use the getChars() method to extract a substring.

str.getChars(13, 19, chArr, 0);

The above substring is an array of characters which can be displayed as shown in the complete example below −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "World is not enough!";
      char[] chArr = new char[10];
      str.getChars(13, 19, chArr, 0);
      for(char res: chArr) {
         System.out.println(res);
      }
   }
}

Output

e
n
o
u
g
h

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 27-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements