如何在Java中混合两个字符串并生成另一个字符串?
字符串用于在Java中存储字符序列,它们被视为对象。java.lang包的String类表示一个字符串。
您可以使用new关键字(像任何其他对象一样)或通过为文字赋值(像任何其他原始数据类型一样)来创建一个字符串。
String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";连接字符串
您可以通过以下方式在Java中连接字符串:
使用“+”运算符 - Java提供了一个连接运算符,使用它,您可以直接添加两个字符串文字
示例
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()方法接受一个字符串值,将其添加到当前字符串并返回连接后的值。
示例
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()方法接受一个字符串值并将其添加到当前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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP