当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。