Extracting a substring as an array of characters in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 14-Dec-2018 06:42:29
Advertisements