[英]How many spaces will Java String.trim() remove?
在 Java 中,我有一個這樣的字符串:
" content ".
String.trim()
刪除這些邊上的所有空格還是每邊一個空格?
從源代碼(反編譯):
public String trim()
{
int i = this.count;
int j = 0;
int k = this.offset;
char[] arrayOfChar = this.value;
while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
++j;
while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
--i;
return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
}
您可以看到的兩個while
表示在開頭和結尾處 unicode 低於空格字符的所有字符都被刪除。
如有疑問,請編寫單元測試:
@Test
public void trimRemoveAllBlanks(){
assertThat(" content ".trim(), is("content"));
}
注意:當然測試(對於 JUnit + Hamcrest)不會失敗
不過,需要指出的一件事是 String.trim 對“空白”有一個特殊的定義。 它不會刪除 Unicode 空格,但也會刪除您可能不考慮空格的 ASCII 控制字符。
此方法可用於從字符串的開頭和結尾修剪空格; 事實上,它還修剪了所有 ASCII 控制字符。
如果可能,您可能希望使用 Commons Lang 的 StringUtils.strip(),它也處理 Unicode 空格(並且也是空安全的)。
請參閱 String 類的API :
返回字符串的副本,省略前導和尾隨空格。
兩邊的空白被刪除:
請注意, trim()
不會更改 String 實例,它將返回一個新對象:
String original = " content ";
String withoutWhitespace = original.trim();
// original still refers to " content "
// and withoutWhitespace refers to "content"
根據此處的 Java 文檔, .trim()
替換了通常稱為空格的 '\ '。
但請注意, '\ ' ( Unicode NO-BREAK SPACE
)也被視為空格,並且.trim()
不會刪除它。 這在 HTML 中尤為常見。
要刪除它,我使用:
tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");
此處討論了此問題的一個示例。
Java trim()
刪除空格的示例:
public class Test
{
public static void main(String[] args)
{
String str = "\n\t This is be trimmed.\n\n";
String newStr = str.trim(); //removes newlines, tabs and spaces.
System.out.println("old = " + str);
System.out.println("new = " + newStr);
}
}
輸出
old =
This is a String.
new = This is a String.
來自 java docs(String class source),
/**
* Returns a copy of the string, with leading and trailing whitespace
* omitted.
* <p>
* If this <code>String</code> object represents an empty character
* sequence, or the first and last characters of character sequence
* represented by this <code>String</code> object both have codes
* greater than <code>'\u0020'</code> (the space character), then a
* reference to this <code>String</code> object is returned.
* <p>
* Otherwise, if there is no character with a code greater than
* <code>'\u0020'</code> in the string, then a new
* <code>String</code> object representing an empty string is created
* and returned.
* <p>
* Otherwise, let <i>k</i> be the index of the first character in the
* string whose code is greater than <code>'\u0020'</code>, and let
* <i>m</i> be the index of the last character in the string whose code
* is greater than <code>'\u0020'</code>. A new <code>String</code>
* object is created, representing the substring of this string that
* begins with the character at index <i>k</i> and ends with the
* character at index <i>m</i>-that is, the result of
* <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
* <p>
* This method may be used to trim whitespace (as defined above) from
* the beginning and end of a string.
*
* @return A copy of this string with leading and trailing white
* space removed, or this string if it has no leading or
* trailing white space.
*/
public String trim() {
int len = count;
int st = 0;
int off = offset; /* avoid getfield opcode */
char[] val = value; /* avoid getfield opcode */
while ((st < len) && (val[off + st] <= ' ')) {
st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}
請注意,在獲取 start 和 length 后,它會調用 String 類的 substring 方法。
trim()
將刪除所有前導和尾隨空格。 但請注意:您的字符串沒有改變。 trim()
將返回一個新的字符串實例。
如果您的字符串輸入是:
String a = " abc ";
System.out.println(a);
是的,輸出將是,“abc”; 但是如果你的字符串輸入是:
String b = " This is a test "
System.out.println(b);
輸出將是This is a test
因此,trim 僅刪除字符串中第一個字符之前和最后一個字符之后的空格,並忽略內部空格。 這是我的一段代碼,它稍微優化了內置的String
trim 方法,刪除內部空格並刪除字符串中第一個和最后一個字符前后的空格。 希望能幫助到你。
public static String trim(char [] input){
char [] output = new char [input.length];
int j=0;
int jj=0;
if(input[0] == ' ' ) {
while(input[jj] == ' ')
jj++;
}
for(int i=jj; i<input.length; i++){
if(input[i] !=' ' || ( i==(input.length-1) && input[input.length-1] == ' ')){
output[j]=input[i];
j++;
}
else if (input[i+1]!=' '){
output[j]=' ';
j++;
}
}
char [] m = new char [j];
int a=0;
for(int i=0; i<m.length; i++){
m[i]=output[a];
a++;
}
return new String (m);
}
要僅保留 String 的一個實例,您可以使用以下內容。
str = " Hello ";
或者
str = str.trim();
那么str
字符串的值,將是str = "Hello"
它將刪除兩側的所有空格。
一件非常重要的事情是,完全由“空格”組成的字符串將返回一個空字符串。
如果string sSomething = "xxxxx"
,其中x
代表空格, sSomething.trim()
將返回一個空字符串。
如果string sSomething = "xxAxx"
,其中x
代表空格, sSomething.trim()
將返回A
。
如果sSomething ="xxSomethingxxxxAndSomethingxElsexxx"
, sSomething.trim()
將返回SomethingxxxxAndSomethingxElse
,注意單詞之間的x
數量沒有改變。
如果您想要一個整潔的打包字符串,請將trim()
與正則表達式結合起來,如這篇文章所示: 如何使用Java 刪除字符串中的重復空格? .
順序對結果毫無意義,但首先使用trim()
會更有效。 希望能幫助到你。
String formattedStr=unformattedStr;
formattedStr=formattedStr.trim().replaceAll("\\s+", " ");
Trim() 對雙方都有效。
String 的Javadoc包含所有詳細信息。 從兩端刪除空格(空格、制表符等)並返回一個新字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.