• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
isuning
博客园    首页    新随笔    联系   管理    订阅  订阅
【Java源码分析】String getChars

在这里插入图片描述

getChars()

getChars() 方法将字符从字符串复制到目标字符数组。

语法
public void getChars(int srcBegin, int srcEnd, char[] dst,  int dstBegin)
参数
  • srcBegin – 字符串中要复制的第一个字符的索引。
  • srcEnd – 字符串中要复制的最后一个字符之后的索引。
  • dst – 目标数组。
  • dstBegin – 目标数组中的起始偏移量。
返回值

没有返回值

实例
public class Test {
    public static void main(String args[]) {
        String str1 = new String("Hello world");
        char[] str2 = new char[6];
        str1.getChars(4, 10, str2, 0);
        System.out.println(str2 );
      
    }
}

以上程序执行结果为:

o worl
源码
  public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
        if (srcBegin < 0) {
            throw new StringIndexOutOfBoundsException(srcBegin);
        }
        if (srcEnd > value.length) {
            throw new StringIndexOutOfBoundsException(srcEnd);
        }
        if (srcBegin > srcEnd) {
            throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
        }//不在数据范围内,抛异常
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

底层采用的是数组

posted on 2022-05-01 22:16  吕布辕门  阅读(50)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3