Java String trim() method is used to remove leading and trailing whitespaces from a string. This method treats any character whose Unicode codepoint is less than or equal to ‘U+0020’ as a whitespace character.
Java String trim()方法用于從字符串中刪除開頭和結尾的空格。 此方法將Unicode碼點小于或等于'U + 0020'的任何字符視為空白字符。
Let’s look at a simple example of String trim() method.
Javaequals。 讓我們看一下String trim()方法的簡單示例。
package com.journaldev.examples;public class StringTrim {public static void main(String[] args) {String str = " abc def \t\t ";System.out.println("***"+str+"***");String str1 = str.trim();System.out.println("***"+str1+"***"); }
}
Output:
輸出:
*** abc def ***
***abc def***
I am appending a few non-whitespace characters while printing the string so that the difference is clearly visible in the output.
Java聲明, 我在打印字符串時附加了一些非空白字符,以使差異在輸出中清晰可見。
Let’s look at another example using the JShell interpreter.
讓我們看一下使用JShell解釋器的另一個示例。
jshell> String str = " abc def \t\t ";
str ==> " abc def \t\t "jshell> str.trim();
$2 ==> "abc def"
Java 11 added many new methods in the string class. One of them is the strip() method that does the same job as the trim() method.
Javatrim, Java 11在字符串類中添加了許多新方法。 其中之一是strip()方法,其功能與trim()方法相同。
However, the strip() method uses Character.isWhitespace() method to check if the character is a whitespace. This method uses Unicode code points whereas trim() method identifies any character having codepoint value less than or equal to ‘U+0020’ as a whitespace character.
但是,strip()方法使用Character.isWhitespace()方法檢查字符是否為空白。 此方法使用Unicode代碼點,而trim()方法將代碼點值小于或等于“ U + 0020”的任何字符標識為空白字符。
The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard.
java tostring方法? 推薦使用strip()方法刪除空格,因為它使用Unicode標準。
翻譯自: https://www.journaldev.com/33291/java-string-trim-method-examples
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态