java怎么去除字符串中的空格

38次阅读
没有评论

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

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

  1. 使用 replaceAll() 函数,通过正则表达式替换空格字符:
String str = "  hello  world  ";
String newStr = str.replaceAll("\\s", "");
System.out.println(newStr);

输出:helloworld

  1. 使用 replace() 函数,将空格字符替换为空字符串:
String str = "  hello  world  ";
String newStr = str.replace(" ", "");
System.out.println(newStr);

输出:helloworld

  1. 使用 trim() 函数,去除字符串开头和结尾的空格:
String str = "  hello  world  ";
String newStr = str.trim();
System.out.println(newStr);

输出:hello world

注意:以上方法都会去除字符串中所有的空格字符。如果只想去除开头和结尾的空格字符,可以使用 trim() 函数;如果想保留字符串中的部分空格字符,可以根据具体需求自定义正则表达式。

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

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