学习使用String类的strip(), stripLeading()和 stripTrailing()方法来删除不需要的空格来自 Java 11 中的给定字符串。
字符串strip()
从Java 11开始,String 类包含3个其他方法,这些方法有助于消除多余空格。使用 Character.isWhitespace(char) 方法来确定空白字符。
- String strip() – 返回一个字符串,其值指定为字符串,并且所有左右空格都已删除。
- 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 !!"
}
}
正则去除空白
在不使用Java 11的情况下,可以使用正则表达式来修剪字符串周围的空格。
| 正则表达式 | 说明 |
|---|---|
| ^ [\t] + | [\t] + $ | 删除前导空格和尾随空格 |
| ^ [\t] + | 仅删除前导空白 |
| [\t] + $ | 仅删除尾随空格 |
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 !!"
}
}
链接:https://www.learnfk.com/article-java11-strip-remove-white-spaces
来源:Learnfk无涯教程
