English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
문자열은 Java에서 문자열을 저장하는 데 사용되며, 이들은 대상으로 간주됩니다. java.lang 패키지의 String 클래스는 String을 나타냅니다.
String을 생성할 수 있습니다. new 키워드(그 외의 대상과 마찬가지로)를 사용하거나, 값이 할당된 문자열(그 외의 원시 데이터 타입과 마찬가지로)을 사용하여 생성할 수 있습니다.
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