Java StringBuffer getChars()方法及示例

来源:这里教程网 时间:2026-02-17 21:13:38 作者:

Java StringBuffer getChars()方法及示例

StringBuffer类getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) 方法从实际序列中复制从index:srcBegin到index:srcEnd-1的字符到一个作为参数传递给函数的char数组中。

这些字符被复制到char dst[]数组中,从index:dstBegin开始,到index:dstbegin+(srcEnd-srcBegin)-1结束。第一个被复制到数组中的字符位于索引 srcBegin,最后一个被复制的字符位于索引 srcEnd-1。要复制的字符总数等于srcEnd-srcBegin。

语法

public void getChars(int srcBegin, int srcEnd,                           char[] dst, int dstBegin)

参数: 本方法需要四个参数。

srcBegin :int值,代表要开始复制的索引。srcEnd :int值,代表要停止复制的索引。dst :char数组,表示要将数据复制到的数组。dstBegin :int值,代表开始粘贴复制数据的dst数组的索引。

返回: 该方法不返回任何东西。
异常: 该方法会抛出StringIndexOutOfBoundsException,如果。

srcBegin < 0dstBegin < 0srcBegin > srcEndsrcEnd > this.length()dstBegin+srcEnd-srcBegin > dst.length

下面的程序演示了StringBuffer类的getChars()方法:

例1 :

// Java program to demonstrate// the getChars() Method. import java.util.*; class GFG {    public static void main(String[] args)    {         // create a StringBuffer object        // with a String pass as parameter        StringBuffer            str            = new StringBuffer("Geeks For Geeks");         // print string        System.out.println("String = "                           + str.toString());         // create a char Array        char[] array = new char[15];         // initialize all character to .(dot).        Arrays.fill(array, '.');         // get char from index 0 to 9        // and store in array start index 3        str.getChars(0, 9, array, 1);         // print char array after operation        System.out.print("char array contains : ");         for (int i = 0; i < array.length; i++) {            System.out.print(array[i] + " ");        }    }}

输出

String = Geeks For Geekschar array contains : . G e e k s   F o r . . . . .

例2: 演示StringIndexOutOfBoundsException。

// Java program to demonstrate// exception thrown by the getChars() Method. import java.util.*; class GFG {    public static void main(String[] args)    {         // create a StringBuffer object        // with a String pass as parameter        StringBuffer            str            = new StringBuffer("Contribute Geeks");         // create a char Array        char[] array = new char[10];         // initialize all character to (dollar sign).        Arrays.fill(array, '');         try {             // if start is greater then end            str.getChars(2, 1, array, 0);        }         catch (Exception e) {            System.out.println("Exception: " + e);        }    }}

输出

Exception: java.lang.StringIndexOutOfBoundsException: srcBegin > srcEnd

**参考文献: ** https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#getChars(int, int, char%5B%5D, int)

相关推荐