学习使用String
类的strip()
, stripLeading()
和 stripTrailing()
方法来删除不需要的空格来自 Java 11 中的给定字符串。
从Java 11开始,String
类包含3个其他方法,这些方法有助于消除多余空格。使用 Character.isWhitespace(char) 方法来确定空白字符。
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 !!" } }
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)