Java String类的getChars()方法将此字符串的内容复制到指定的char数组中。在getChars()方法中传递了四个参数。getChars()方法的语法如下:

语法

public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)  

参数

int srcBeginIndex:复制字符的起始索引。

int srcEndIndex:复制的最后一个字符后面的索引。

char[] destination:调用getChars()方法的字符串的字符将被复制到的char数组。

int dstEndIndex:表示从哪个位置开始将字符串的字符推入目标数组。

返回值

它不返回任何值。

异常抛出

当以下任何一个或多个条件成立时,该方法会抛出StringIndexOutOfBoundsException异常:

  • 如果srcBeginIndex小于零。
  • 如果srcBeginIndex大于srcEndIndex。
  • 如果srcEndIndex大于调用该方法的字符串的大小
  • 如果dstEndIndex小于零。
  • 如果dstEndIndex + (srcEndIndex - srcBeginIndex)大于目标数组的大小。

内部实现

getChars()方法的签名或语法如下:

void getChars(char dst[], int dstBegin) {    
        // 将值从 0 复制到 dst - 1  
        System.arraycopy(value, 0, dst, dstBegin, value.length);    
    }  

Java String getChars()方法示例

文件名:StringGetCharsExample.java

public class StringGetCharsExample{  
public static void main(String args[]){  
 String str = new String("hello javatpoint how r u");  
      char[] ch = new char[10];  
      try{  
         str.getChars(6, 16, ch, 0);  
         System.out.println(ch);  
      }catch(Exception ex){System.out.println(ex);}  
}}  

输出:

javatpoint

Java String getChars()方法示例2

如果索引值超出数组范围,该方法将抛出异常。让我们看一个示例。

文件名:StringGetCharsExample2.java

public class StringGetCharsExample2 {  
    public static void main(String[] args) {  
        String str = new String("Welcome to Javatpoint");  
        char[] ch  = new char[20];  
        try {  
            str.getChars(1, 26, ch, 0);  
            System.out.println(ch);  
        } catch (Exception e) {  
            System.out.println(e);  
        }  
    }  
}  

输出:

java.lang.StringIndexOutOfBoundsException: offset 10, count 14, length 20

Java String getChars()方法示例3

如果srcBeginIndex和srcEndIndex的值相同,则getChars()方法不会将任何内容复制到char数组中。这是因为getChars()方法从srcBeginIndex索引复制到srcEndIndex - 1索引。由于srcBeginIndex等于srcEndIndex,因此srcEndIndex - 1小于srcBeginIndex。因此,getChars()方法不复制任何内容。以下示例确认了这一点。

文件名:StringGetCharsExample3.java

public class StringGetCharsExample3   
{  
// 主要方法 
public static void main(String argvs[])  
{  
String str = "Welcome to JavaTpoint!";  
  
// 创建一个大小为 25 的字符集 
char[] chArr = new char[25];    
  
// 开始和结束索引相同 
int srcBeginIndex = 11;  
int srcEndIndex = 11;  
int dstBeginIndex = 2;  
  
try  
{    
// 调用方法 getChars()  
str.getChars(srcBeginIndex, srcEndIndex, chArr, dstBeginIndex);    
System.out.println(chArr);    
}  
catch(Exception excpn)  
{  
System.out.println(excpn);  
}  
System.out.println("The getChars() method prints nothing as start and end indices are equal.");    
}  
}  

输出:

The getChars() method prints nothing as start and end indices are equal.

标签: java, Java面试题, Java下载, java教程, java技术, Java学习, Java学习教程, Java语言, Java开发, Java入门教程, Java进阶教程, Java高级教程, Java笔试题, Java编程思想