如何在 Java 中混合两个字符串并生成另一个字符串?

javaobject oriented programmingprogramming更新于 2024/2/11 3:24:17

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() 方法接受一个 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

相关文章


有用资源