Java String Spacing: Add Spaces Between Strings

There are multiple methods in Java to add spaces between strings, below are some commonly used methods:

  1. Concatenate strings and spaces using the “+” symbol.
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
System.out.println(result); // 输出 "Hello World"
  1. Using the append method of the StringBuilder class:
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. Use the String.join method:
String str1 = "Hello";
String str2 = "World";
String result = String.join(" ", str1, str2);
System.out.println(result); // 输出 "Hello World"
  1. By using the String.format method:
String str1 = "Hello";
String str2 = "World";
String result = String.format("%s %s", str1, str2);
System.out.println(result); // 输出 "Hello World"
bannerAds