Java 11 – 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 !!"
	}
}

鏈接:https://www.learnfk.com/article-java11-strip-remove-white-spaces
來源:Learnfk無涯教程

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM