English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java中几种方式连接字符串的方法

字符串用于在Java中存储一系列字符,它们被视为对象。java.lang包的String类表示一个String。

您可以通过使用new关键字(如任何其他对象)或通过将值分配给文字(如任何其他原始数据类型)来创建String。

String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";

连接字符串

您可以通过以下方式在Java中连接字符串-

使用“ +”运算符:Java使用此运算符提供了一个串联运算符,您可以直接添加两个String文字

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1+str2;
      System.out.println(result);
   }
}

输出结果

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Java

使用concat()方法 -String类的concat()方法接受一个String值,将其添加到当前String中并返回串联的值。

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1.concat(str2);
      System.out.println(result);
   }
}

输出结果

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap

使用StringBuffer和StringBuilder类 -当需要修改时,StringBuffer和StringBuilder类可以用作String的替代类。

它们与String相似,但它们是可变的。这些提供了用于内容操纵的各种方法。这些类的append()方法接受一个String值,并将其添加到当前的StringBuilder对象中。

示例

import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      StringBuilder sb = new StringBuilder(str1);
      //Concatenating the two Strings
      sb.append(str2);
      System.out.println(sb);
   }
}

输出结果

Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap