Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-01-06) 阅读数 6 #程序编程
文章标签 Java

在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"
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门