溫馨提示×

Java中怎么在字符串之間添加空格

小億
299
2024-03-01 12:15:13
欄目: 編程語言

在Java中在字符串之間添加空格有多種方法,下面列舉了幾種常用的方法:

  1. 使用"+"連接字符串和空格:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // 輸出 "Hello World"
  1. 使用StringBuilder類的append方法:
String str1 = "Hello";
String str2 = "World";
StringBuilder sb = new StringBuilder();
sb.append(str1).append(" ").append(str2);
String result = sb.toString();
System.out.println(result); // 輸出 "Hello World"
  1. 使用String.join方法:
String str1 = "Hello";
String str2 = "World";
String result = String.join(" ", str1, str2);
System.out.println(result); // 輸出 "Hello World"
  1. 使用String.format方法:
String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 輸出 "Hello World"

0