java中String的连接符代码示例

该类String包括一个连接两个字符串的方法:

string1.concat(string2);

这将返回一个新字符串,该字符串string1在string2末尾添加。

您还可以将该concat()方法与字符串文字一起使用,如下所示:

"My name is ".concat("Rumplestiltskin");

字符串更常与+运算符连接,如

"Hello,"+" world"+"!"

这导致

"Hello, world!"

该+运算符广泛用于打印语句。例如:

Stringstring1="saw I was ";System.out.println("Dot "+string1+"Tod");

哪个打印

Dot saw I was Tod

这样的连接可以是任何对象的混合。对于每个不是 a 的对象,调用String其toString()方法将其转换为 a String。

注意:在 Java SE 15 之前,Java 编程语言不允许文字字符串跨越源文件中的行,因此您必须+在多行字符串的每行末尾使用连接运算符。例如:

Stringquote="Now is the time for all good "+"men to come to the aid of their country.";

+再一次,使用连接运算符在行之间断开字符串在print语句中非常常见。

从 Java SE 15 开始,您可以编写二维字符串文字:

Stringhtml=""" <html> <body> <p>Hello, world</p> </body> </html> """;
java中String的连接符代码示例

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注