Java中去除前导/尾随空格

培训教学 潘老师 8个月前 (09-11) 180 ℃ (0) 扫码查看

本教程演示了如何使用正则表达式和Java 11中的新String.strip() API来去除Java字符串中的去除首尾空格

1.简介

字符串开头的空白字符称为前导空白字符,而字符串末尾的空白字符称为尾随空白字符。虽然我们可以使用正则表达式和其他方法来修剪空格,但自Java 11以来,建议使用strip()方法。

2.去除前导空白字符

2.1. 使用String.stripLeading()

在Java 11中添加了stripLeading()方法。它返回一个字符串,其中所有前导空白字符都被移除。

String blogName = "    how to do in java    ";
String strippedLeadingWhitespaces = blogName.stripLeading();
Assertions.assertEquals(strippedLeadingWhitespaces, "how to do in java    ");

2.2. 使用正则表达式

这个Java示例利用了正则表达式和String的replaceAll()方法来查找所有前导空白字符。一旦我们找到了所有前导空白字符,就可以用空字符串替换它们。

String regex = "^\\s+";
String trimmedLeadingWhitespaces = blogName.replaceAll(regex, "");
Assertions.assertEquals(trimmedLeadingWhitespaces, "howtodoinjava    ");

或者我们可以使用相同的正则表达式来匹配字符串开头的空白字符,并使用replaceFirst()方法替换它们。

String regex = "^\\s+";
String trimmedLeadingWhitespaces = blogName.replaceFirst(regex, "");
Assertions.assertEquals("howtodoinjava    ", trimmedLeadingWhitespaces);

3.去除尾随空白字符

3.1. 使用String.stripTrailing()

stripTrailing()方法返回一个去除了所有尾随空白字符的字符串。

String blogName = "    how to do in java    ";
String strippedTrailingWhitespaces = blogName.stripTrailing();
Assertions.assertEquals(strippedTrailingWhitespaces , "how to do in java    ");

3.2. 使用正则表达式

从字符串末尾移除空白字符的方法与前面的示例非常相似。只是正则表达式需要更改以匹配末尾的空白字符。

String regex = "\\s+$";
String trimmedTrailingWhitespaces = blogName.replaceAll(regex, "");
Assertions.assertEquals("    how to do in java", trimmedTrailingWhitespaces);

4.去除前导和尾随空白字符

4.1. 使用String.trim()

如果我们想要从字符串中删除首尾空白字符,最好的方法是使用String.trim()方法。

String blogName = "    how to do in java    ";
String trimmedString = blogName.trim();
Assertions.assertEquals("how to do in java", trimmedString);

4.2. 使用String.strip()

自Java 11以来,我们还可以使用strip()方法。

String blogName = "    how to do in java    ";
String strippedString = blogName.strip();
Assertions.assertEquals("how to do in java", strippedString);

使用上面提供的示例来从Java中的字符串中去除前导和尾随空白字符,你学会了吗?


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/teach/8963.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】