Javaequals,Java String trim()方法示例

 2023-11-19 阅读 28 评论 0

摘要: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()方法用于

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'的任何字符視為空白字符。

  • If the string contains only whitespaces, an empty string is returned.

    如果字符串僅包含空格,則返回一個空字符串。
  • If there are no leading and trailing whitespaces in the string, the reference to the same string is returned.

    如果字符串中沒有開頭和結尾的空格,則返回對同一字符串的引用。
  • Java String is immutable, so the original string object value remains unchanged.

    Java String是不可變的 ,因此原始字符串對象的值保持不變。

Java字符串trim()示例 (Java String trim() Example)

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"

字符串trim()vs strip()方法 (String trim() vs strip() Method)

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標準。

參考資料 (References)

  • String API Docs

    字符串API文檔
  • Java 11: New Methods in String Class

    Java 11:字符串類中的新方法

翻譯自: https://www.journaldev.com/33291/java-string-trim-method-examples

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/183303.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息