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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:29   3241   0

字符串用于在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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP