编写一个Java程序来连接字符串,并附带示例。有多种方法可以执行字符串连接,我们涵盖了其中大多数。我们可以使用内置函数,包括concat()、StringBuilder和StringBuffer的append函数。除此以外,还可以使用算术+运算符来实现相同的目的。
Java 字符串连接程序
在此示例中,我们允许用户输入两个不同的字符串。接下来,使用String函数将con_str2连接到con_str1,并将输出分配给一个新的字符串str3。
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
String con_str1;
String con_str2;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter the first : ");
con_str1 = sc.nextLine();
System.out.print("\nPlease Enter the second : ");
con_str2 = sc.nextLine();
String str3 = con_str1.concat(con_str2);
System.out.println("\nThe result = " + str3);
}
}
Please Enter the first : Hi
Please Enter the second : Hello
The result = HiHello
使用算术运算符+
在此程序中,我们使用了算术运算符+进行字符串连接。默认情况下,+运算符将相加两个数字,如果您在文本中使用它,它将连接它们,因此我们使用此+算术运算符来连接给定的字符串。但是,要在两个单词之间添加空格,必须在单词之间使用“ ”。
import java.util.Scanner;
public class ConcatStrings1 {
private static Scanner sc;
public static void main(String[] args) {
String conStr1;
String conStr2;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter the first String : ");
conStr1 = sc.nextLine();
System.out.print("\nPlease Enter the second String : ");
conStr2 = sc.nextLine();
String str3 = conStr1 + ' ' + conStr2;
System.out.println("\nThe Java String concat result = " + str3);
}
}

使用StringBuilder连接字符串的Java程序
首先,我们必须创建一个具有最佳大小的StringBuilder实例。接下来,StringBuilder有一个append函数,该函数将一个字符串附加到另一个字符串的末尾。
import java.util.Scanner;
public class Example2 {
private static Scanner sc;
public static void main(String[] args) {
String conStr1;
String conStr2;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter the first : ");
conStr1 = sc.nextLine();
System.out.print("\nPlease Enter the second : ");
conStr2 = sc.nextLine();
StringBuilder sb = new StringBuilder(15);
sb.append(conStr1).append(" ").append(conStr2);
System.out.println("\nThe result = " + sb.toString());
}
}

使用StringBuffer的append
与StringBuilder类似,StringBuffer也有一个append()函数,该函数将一个字符串连接到另一个字符串的末尾。
import java.util.Scanner;
public class Example3 {
private static Scanner sc;
public static void main(String[] args) {
String conStr1;
String conStr2;
sc= new Scanner(System.in);
System.out.print("\nPlease Enter the first : ");
conStr1 = sc.nextLine();
System.out.print("\nPlease Enter the second : ");
conStr2 = sc.nextLine();
StringBuffer sbuff = new StringBuffer(15);
sbuff.append(conStr1).append(" ").append(conStr2);
System.out.println("\nResult = " + sbuff.toString());
}
}
