programing

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

yoursource 2022. 12. 21. 23:10
반응형

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

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

예를 들어 다음과 같습니다.

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

결과:

no spaces:keep this

myString.replace(" ","")keep와 이 사이의 공간을 대체할 수 있습니다.

trim() 메서드를 사용해 볼 수 있습니다.

String newString = oldString.trim();

javadocs 보기

사용방법 또는String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")양끝을 다듬습니다.

왼쪽 트림의 경우:

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

오른쪽 트림의 경우:

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

문서에서:

String.trim();

trim()은 사용자가 선택할 수 있지만replacemethod -- 보다 유연성이 높은 경우, 다음을 시험해 볼 수 있습니다.

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

Java-11 이후에서는 API를 사용하여 선행 및 후행 공백이 모두 제거된 상태에서 이 문자열의 값을 가진 문자열을 반환할 수 있습니다.동일한 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)*$", "")

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

s.strip()은 Java 11 이후부터 사용할 수 있습니다.

사용할 수 있습니다.

private void capitaliseEveryWordInASentence() {

    String mm = "Hello there, this is the cluster";

    String[] words = mm.split(" ");
    String outt = "";

    for (String w : words) {

        outt = outt + Character.toUpperCase(w.charAt(0)) + w.substring(1) + " ";
    }

    System.out.println(outt.trim());
}

언급URL : https://stackoverflow.com/questions/6652687/strip-leading-and-trailing-spaces-from-java-string

반응형