[java] Java 문자열에서 선행 및 후행 공백 제거

Java 문자열에서 선행 또는 후행 공백을 제거하는 편리한 방법이 있습니까?

다음과 같은 것 :

String myString = "  keep this  ";
String stripppedString = myString.strip();
System.out.println("no spaces:" + strippedString);

결과:

no spaces:keep this

myString.replace(" ","") keep과 this 사이의 공간을 대체합니다.



답변

trim () 메소드를 시도 할 수 있습니다.

String newString = oldString.trim();

javadocs 살펴보기


답변

String#trim()방법을 사용 하거나 String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")양쪽 끝을 다듬 으십시오.

왼쪽 트림의 경우 :

String leftRemoved = myString.replaceAll("^\\s+", "");

오른쪽 트림의 경우 :

String rightRemoved = myString.replaceAll("\\s+$", "");


답변

로부터 문서 :

String.trim();


답변

trim ()이 선택되지만 replace더 융통성있는 메소드 를 사용 하려면 다음을 시도하십시오.

String stripppedString = myString.replaceAll("(^ )|( $)", "");


답변

Java-11 이상에서는 String.stripAPI를 사용하여 값이이 문자열 인 문자열을 리턴 할 수 있습니다. 모든 선행 및 후행 공백은 제거됩니다. 동일한 읽기에 대한 javadoc은 다음과 같습니다.

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

이에 대한 샘플 사례는 다음과 같습니다 .–

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"


답변

특정 문자를 자르려면 다음을 사용할 수 있습니다.

String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")

여기에 선행 및 후행 공백쉼표를 제거 합니다.


답변