Java11 - String.strip()

Java11 - String.strip() 首页 / Java入门教程 / Java11 - String.strip()

学习使用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 !!"
	}
}

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

左耳听风 -〔陈皓〕

深入浅出区块链 -〔陈浩〕

深入剖析Kubernetes -〔张磊〕

白话法律42讲 -〔周甲徳〕

iOS开发高手课 -〔戴铭〕

WebAssembly入门课 -〔于航〕

深度学习推荐系统实战 -〔王喆〕

说透芯片 -〔邵巍〕

现代C++20实战高手课 -〔卢誉声〕

好记忆不如烂笔头。留下您的足迹吧 :)