Java 中的字符串连接
字符串连接是连接两个或多个字符串的操作。在 Java 中,我们可以使用不同的方法连接字符串。 以下是连接字符串的一些方法:
使用 + 运算符
使用字符串 concat() 方法
使用 stringBuilder 或 stringBuffer 类
使用 + 运算符进行字符串连接
+ 运算符是连接两个 字符串 的简单方法,它直接在两个操作数(字符串)之间执行连接操作。由于其简单性,这是一种常用的方法。
示例
以下示例显示了使用"+"运算符方法进行字符串连接 -
public class ConncatSample { public static void main(String []args) { String s1 = "Hello"; String s2 = "world"; String res = s1 + s2; System.out.print("Concatenation result:: "); System.out.println(res); } }
输出
Concatenation result:: Helloworld
使用 concat() 方法进行字符串连接
字符串 concat() 方法 将一个字符串连接到另一个字符串的末尾。它将两个字符串组合起来并返回结果。如果任何一个字符串为空,则会抛出 NullPointerException。
示例
以下示例显示使用 concat() 方法连接字符串 −
public class HelloWorld { public static void main(String []args) { String s = "Hello"; s = s.concat("world"); System.out.print(s); } }
输出
Helloword
使用 stringBuilder 或 stringBuffer 类
类 StringBuilder 提供 append() 方法 来执行连接操作,它接受各种类型的输入参数,即 Objects、StringBuilder、int、char、CharSequence、boolean、float、double。stringbuilder 是 Java 中连接字符串的最快和最流行的方法。
示例
以下示例显示使用 stringBuilder 或 stringBuffer 类连接字符串 −
public class StringBuilderExample { public static void main(String[] args) { String firstName = "Mark"; String lastName = "Smith"; // 使用 StringBuilder 实现高效的字符串连接 StringBuilder sb = new StringBuilder(); sb.append("Hello, "); sb.append(firstName); sb.append(" "); sb.append(lastName); String result = sb.toString(); System.out.println(result); } }
输出
Hello, Mark Smith
java_strings.html