使用 String类的 strip()、stripLeading()和 stripTrailing()方法从 Java 11 中的给定字符串中删除不需要的空格。
String strip() API
从 Java 11 开始,String类包含另外 3 个有助于删除另外空格的方法。
这些方法使用 Character.isWhitespace(char) 方法来确定空白字符。
- String strip() - 返回一个字符串,其值为给定的字符串,删除了所有前导和尾随空格。请注意,
String.trim()方法也会产生相同的结果。 - String stripLeading() - 返回一个字符串,其值为给定的字符串,去除了所有前导空格。
- String stripTrailing() - 返回一个字符串,其值为给定的字符串,并删除所有尾随空格。
public class Main
{
public static void main(String[] args)
{
String str = " Hello World !! ";
System.out.println( str.strip() ); //"Hello World !!"
System.out.println( str.stripLeading() ); //"Hello World !! "
System.out.println( str.stripTrailing() ); //" Hello World !!"
}
}
更多: zhilu jiaocheng
使用正则表达式修剪空格(包括制表符)
如果我们没有使用 Java 11,那么我们可以使用正则表达式来修剪字符串周围的空格。
| 表达式 | 描述 |
|---|---|
| ^[ ]+|[ ]+$ | 删除前导和尾随空格 |
| ^[ ]+ | 仅删除前导空格 |
| [ ]+$ | 仅删除尾随空格 |
public class Main
{
public static void main(String[] args)
{
String str = " Hello World !! ";
System.out.println( str.replaceAll("^[ \t]+|[ \t]+$", "") ); //"Hello World !!"
System.out.println( str.replaceAll("^[ \t]+", "") ); //"Hello World !! "
System.out.println( str.replaceAll("[ \t]+$", "") ); //" Hello World !!"
}
}
日期:2020-09-17 00:09:38 来源:oir作者:oir
