Java-Extracting Characters

Extracting Characters

If we wish to extract more than one character at a time from a string, we have to use the getChars( ) method. For example, in the following program, the characters staring from the position ‘5’ and ending with the position ’16-1′ will be extracted and then stored in the character array ‘str1′ from the position ‘0’ in the array ‘str1′. Thus, in this example, ‘str1′ will contain “Programming”. The companion method for the getChars( ) method is the toCharArray( ). This method converts an entire string into an array of type char.

Program

1

Program Source

public class Javaapp {
    
    public static void main(String[] args){
        
        String str = new String("Java Programming Tutorials");
        char[] str1 = new char[11];
        str.getChars(5, 16, str1, 0);
        System.out.println("char[] str1 = "+String.valueOf(str1));
        
        char[] str2 = str.toCharArray();
        System.out.println("char[] str2 = "+String.valueOf(str2));
   }
}

Leave a Comment