The method getChars()
is used for copying String
characters to an Array of chars.
public void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
Parameters description:
srcBegin – index of the first character in the string to copy.
srcEnd – index after the last character in the string to copy.
dest – Destination array of characters in which the characters from String gets copied.
destBegin – The index in Array starting from where the chars will be pushed into the Array.
It throws IndexOutOfBoundsException – If any of the following conditions occurs:
(srcBegin<0
) srcBegin is less than zero. (srcBegin>srcEnd) srcBegin is greater than srcEnd.
(srcEnd > length of string
) srcEnd is greater than the length of this string.
(destBegin<0
) destBegin
is negative.
dstBegin+(srcEnd-srcBegin)
is larger than dest.length
.
Example: getChars() method
public class GetCharsExample{ public static void main(String args[]){ String str = new String("This is a String Handling Tutorial"); char[] array = new char[6]; str.getChars(10, 16, array, 0); System.out.println("Array Content:" ); for(char temp: array){ System.out.print(temp); } char[] array2 = new char[]{'a','a','a','a','a','a','a','a'}; str.getChars(10, 16, array2, 2); System.out.println("Second Array Content:" ); for(char temp: array2){ System.out.print(temp); } } }
Output:
Array Content: StringSecond Array Content: aaString
E says
Is there a typo or is Array Content not supposed to print anything?
E says
Sorry, I see now why there is no output for Array Content! Is it because String is not an array ?
E says
Correction: I see it’s because indices 10 and 16 give spaces!
E says
Why does String print out in the secondarray content though? I realize there should probably be a new line in front of “Second Array Content” to avoid confusion.