溫馨提示×

Java strip函數新特性解讀

小樊
125
2024-06-26 11:35:44
欄目: 編程語言

在Java 11中,引入了一個新的方法strip(),用于去除字符串的首尾空格。這個方法與trim()方法類似,但是strip()方法比trim()方法更強大,因為它可以去除Unicode空格字符,而不僅僅是ASCII空格字符。

strip()方法的使用非常簡單,只需要在字符串上調用該方法即可。例如:

String str = "  Hello World  ";
String strippedStr = str.strip();
System.out.println(strippedStr); // 輸出:Hello World

除了strip()方法之外,還引入了stripLeading()stripTrailing()方法,分別用于去除字符串的開頭和結尾的空格。使用這兩個方法的示例如下:

String str = "  Hello World  ";
String strippedLeadingStr = str.stripLeading();
String strippedTrailingStr = str.stripTrailing();
System.out.println(strippedLeadingStr); // 輸出:Hello World  
System.out.println(strippedTrailingStr); // 輸出:  Hello World

總的來說,strip()方法為處理字符串中的空格字符提供了更加靈活和便捷的方法,使得代碼更加簡潔和易讀。

0