温馨提示×

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

小亿
87
2024-03-12 18:51:39
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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"

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

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Java trimend如何去除字符串空格

0