Java String getChars()

2025 年 3 月 24 日 | 阅读 3 分钟

Java String 类的 getChars() 方法将此字符串的内容复制到指定的字符数组中。getChars() 方法有四个参数。getChars() 方法的签名如下

签名

参数

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

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

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

int dstEndIndex: 它表示目标数组中将要从该位置开始插入字符串中字符的位置。

返回值

它不返回任何值。

异常抛出

当满足以下一个或多个条件时,该方法会抛出 StringIndexOutOfBoundsException。

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

内部实现

字符串 getChars() 方法的签名或语法如下

Java String getChars() 方法示例

示例

编译并运行

输出

TpointTech

Java String getChars() 方法示例 2

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

示例

编译并运行

输出

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() 方法不复制任何内容。以下示例证实了这一点。

示例

编译并运行

输出

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