當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java String getChars()用法及代碼示例


Java字符串getChars()方法將給定字符串中的字符複製到目標字符數組中。

用法:

public void getChars(int srhStartIndex, 
int srhEndIndex, char[] destArray, int destStartIndex)     
參數:
srhStartIndex:Index of the first character in the string to copy. 
srhEndIndex:Index after the last character in the string to copy.
destArray:Destination array where chars wil get copied.
destStartIndex:Index in the array starting from where the chars
                 will be pushed into the array.
返回: It does not return any value.

異常: StringIndexOutOfBoundsException-如果srhStartIndex,srhEndIndex不在適當範圍內。


例:展示getChars()方法的用法原理

// Java program to demonstrate 
// working of getChars() method 
  
class Gfg1 { 
    public static void main(String args[]) 
    { 
        String str = "Welcome! to GeeksforGeeks"; 
  
        char[] destArray = new char[20]; 
        try { 
            str.getChars(12, 25, destArray, 0); 
            System.out.println(destArray); 
        } 
        catch (Exception ex) { 
            System.out.println(ex); 
        } 
    } 
}

輸出:

GeeksforGeeks
// Java program to demonstrate 
// exception condition in 
// working of getChars() method 
  
class Gfg2 { 
    public static void main(String args[]) 
    { 
        String str = "Welcome! to GeeksforGeeks"; 
  
        char[] destArray = new char[20]; 
        try { 
            // Starting index 0 and ending index 24 
            str.getChars(12, 26, destArray, 0); 
            System.out.println(destArray); 
        } 
        catch (Exception ex) { 
            System.out.println(ex); 
        } 
    } 
}

輸出:

java.lang.StringIndexOutOfBoundsException:String index out of range:26


相關用法


注:本文由純淨天空篩選整理自Niraj_Pandey大神的英文原創作品 Java String getChars() with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。