0
点赞
收藏
分享

微信扫一扫

【Java源码分析】String 字符串连接 concat

微言记 2022-04-22 阅读 54
java

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)字符数组

举报

相关推荐

0 条评论