java去除字符串空格的方法是什么

38次阅读
没有评论

共计 459 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,可以使用以下方法去除字符串中的空格:

  1. 使用 trim() 方法去除字符串两端的空格:
String str = "  hello world  ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 输出: "hello world"
  1. 使用 replaceAll() 方法去除字符串中所有空格:
String str = "  hello world  ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
  1. 使用 replace() 方法去除字符串中所有空格:
String str = "  hello world  ";
String noSpaceStr = str.replace(" ", "");
System.out.println(noSpaceStr); // 输出: "helloworld"

这些方法可以根据具体需求选择使用哪种去除空格的方式。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-03-19发表,共计459字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)