Сколько пробелов удалит Java String.trim ()? - PullRequest
119 голосов
/ 04 февраля 2010

В Java у меня есть такая строка:

"     content     ".

Будет ли String.trim() удалять все пробелы с этих сторон или только один пробел с каждой?

Ответы [ 17 ]

169 голосов
/ 04 февраля 2010

Все они .

Returns : Копия этой строки с удаленными начальными и конечными пробелами, или эта строка, если у нее нет начальных или конечных пробелов.

~ Цитируется из документации по Java 1.5.0

(Но почему вы просто не попробовали и сами убедились?)

33 голосов
/ 04 февраля 2010

Из исходного кода (декомпилировано):

  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, которые вы видите, означают, что все символы, чей юникод находится ниже пробела, в начале и в конце удалены.

27 голосов
/ 04 февраля 2010

Если сомневаетесь, напишите модульный тест:

@Test
public void trimRemoveAllBlanks(){
    assertThat("    content   ".trim(), is("content"));
}

NB : конечно, тест (для JUnit + Hamcrest) не проходит

26 голосов
/ 04 февраля 2010

Следует отметить, что String.trim имеет своеобразное определение «пробел». Он не удаляет пробелы в Юникоде, но также удаляет управляющие символы ASCII, которые вы не можете рассматривать как пробелы.

Этот метод может использоваться для обрезки пробелов от начала и конца строки; фактически он также обрезает все управляющие символы ASCII.

Если возможно, вы можете использовать StringUtils.strip () Commons Lang, который также обрабатывает пробельные символы Юникода (и также является нулевым).

15 голосов
/ 04 февраля 2010

См. API для класса String:

Возвращает копию строки, пропуская начальные и конечные пробелы.

Пробелы с обеих сторон удалены:

Обратите внимание, что trim() не изменяет экземпляр String, он возвращает новый объект:

 String original = "  content  ";
 String withoutWhitespace = original.trim();

 // original still refers to "  content  "
 // and withoutWhitespace refers to "content"
13 голосов
/ 30 декабря 2012

Исходя из документов Java здесь , .trim() заменяет '\ u0020', который обычно называют пробелом.

Но учтите, что '\ u00A0' ( Unicode NO-BREAK SPACE &nbsp;) также рассматривается как пробел, и .trim() НЕ удалит это. Это особенно распространено в HTML.

Чтобы удалить его, я использую:

tmpTrimStr = tmpTrimStr.replaceAll("\\u00A0", "");

Пример этой проблемы обсуждался здесь .

8 голосов
/ 02 апреля 2013

Пример 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.
4 голосов
/ 18 декабря 2012

Из документов Java (источник класса String),

/**
 * 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>'&#92;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>'&#92;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>'&#92;u0020'</code>, and let
 * <i>m</i> be the index of the last character in the string whose code
 * is greater than <code>'&#92;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>,&nbsp;<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;
}

Обратите внимание, что после получения начала и длины он вызывает метод подстроки класса String.

3 голосов
/ 04 февраля 2010

trim() удалит все начальные и конечные пробелы.Но знайте: ваша строка не изменилась.trim() вернет новый экземпляр строки.

3 голосов
/ 01 февраля 2015

Если ваш строковый ввод:

String a = "   abc   ";
System.out.println(a);

Да, вывод будет "abc"; Но если ваш ввод String:

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);
  }
...