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

concat()

将指定的字符串连接到此字符串的末尾。

语法
public String concat(String s)
参数
  • s – 要连接的字符串。
返回值

返回连接后的新字符串。

实例
public class Test {
    public static void main(String args[]) {
        String s = "Hello ";
        s = s.concat("world");
        System.out.println(s);
    }
}

以上程序执行结果为:

Hello world
源码
private final char value[];
public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {//长度为0,返回原字符串
            return this;
        }
        int len = value.length;
        //复制原字符串到长度为(len + otherLen)字符数组
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);//复制目标字符串
        return new String(buf, true);
    }

如果连接的字符串长度为0,返回原字符串,否则复制原字符串到长度为(len + otherLen)字符数组

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