Java 将指定字符串连接到此字符串的结尾 concat()

Java 手册

concat

public String concat(String str)
将指定字符串连接到此字符串的结尾。

如果参数字符串的长度为 0,则返回此 String 对象。否则,创建一个新的 String 对象,用来表示由此 String 对象表示的字符序列和参数字符串表示的字符序列连接而成的字符序列。

示例:

 "cares".concat("s") returns "caress"
 "to".concat("get").concat("her") returns "together"
 
参数:
str - 连接到此 String 结尾的 String
返回:
一个字符串,它表示在此对象字符后连接字符串参数字符而成的字符。

实例:

public class Concat {
    public static void main(String[] args) {
        
        String s1 = "cjj ";
        String s2 = "like ";
        String s3 = "lnn";
        
        // 表示将参数拼接到末尾 --- 实际上是返回了一个新的字符串
        // 本质上是利用数组复制产生了一个新的数组
        
        s1 = s1.concat(s2);
        System.out.println(s1); //此时的s1是一个新的字符串
        
        s1 = s1.concat(s3);
        System.out.println(s1);
    }
}

运行结果:

cjj like 
cjj like lnn