CodeGym大学课程体系中包括讲师在线讲座的部分视频。赶快报名吧

“我想告诉你如何合并字符串。合并或连接字符串的过程通常使用简短的词语‘串联’来表示。喜欢猫的人这样记会很容易：con-Cat-en-Nation。开个玩笑。。”

“合并字符串的规则很简单。如果我们将字符串和其他内容‘相加’(+)，则‘其他内容’将通过 toString() 方法隐式地转换为字符串。

“你现在是在跟我说话吗？”

“好吧，我将以更简单的方式进行解释。如果我们将字符串、数字和猫相加，那么数字和猫都会被转换为字符串。下面是一些示例：”

``````Cat cat = new Cat();
String text = "猫是 " + cat;``````
`Cat cat = new Cat();`
` String s = cat.toString();`
` String text = "猫是 " + s;`
``````int a = 5;
String text = "a 是 " + a;``````
`int a = 5;`
` String s = Integer.toString(a);`
` String text = "a 是 " + s;`
``````int a = 5;
String text = a + "a 是 ";``````
`int a = 5;`
` String s = Integer.toString(a);`
` String text = s + "a 是 ";`
``````Cat cat = new Cat();
int a = 5;
String text = "猫是 " + cat + a;``````
`Cat cat = new Cat();`
` String s1 = cat.toString();`
` String s2 = Integer.toString(a);`
` String text = "猫是 " + s1 + s2;`
``````Cat cat = new Cat();
int a = 5;
String text = a + "猫是 " + cat + a;``````
`Cat cat = new Cat();`
` String s1 = cat.toString();`
` String s2 = Integer.toString(a);`
` String s3 = Integer.toString(a);`
` String text = s3 + "猫是 " + s1 + s2;`
``````Cat cat = new Cat();
int a = 5;
String text = cat + a + "猫是 " + cat + a;``````

`String text = (((cat + a) + "猫是 ") + cat) + a;`

``````// 但是你可以这样做：
Cat cat = new Cat();
int a = 5;
String text = cat + (a + "猫是 ") + cat + a;

// 这与以下代码相同：
Cat cat = new Cat();
int a = 5;
String text = ((cat + (a + "猫是 ")) + cat)+a;``````
`Cat cat = new Cat();`
` String s1 = cat.toString();`
` String s2 = cat.toString();`
` String s3 = Integer.toString(a);`
` String s4 = Integer.toString(a);`
` String text = s1 + s3 + "猫是 " + s2 + s4;`

“现在来完成迭戈提供的几个任务。”