반응형
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("(^ )|( $)", "");
함께 자바-11은 지금은 사용 할 수 있습니다 String.strip
제거 모든 선행 및 후행 공백으로, 그 값이 문자열 인 문자열을 반환하는 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)*$", "")
여기서 앞뒤 공백 과 쉼표를 제거 합니다.
참고 URL : https://stackoverflow.com/questions/6652687/strip-leading-and-trailing-spaces-from-java-string
반응형
'Programing' 카테고리의 다른 글
터미널 창의 너비와 높이는 어떻게 찾습니까? (0) | 2020.03.28 |
---|---|
PEM 인코딩 인증서에서 SSL 인증서 만료 날짜를 결정하는 방법은 무엇입니까? (0) | 2020.03.28 |
현재 실행중인 스크립트를로드 한 스크립트 태그를 어떻게 참조합니까? (0) | 2020.03.28 |
파이썬에서 여러 공백을 단일 공백으로 대체 (0) | 2020.03.28 |
fs.readFile에서 데이터 가져 오기 (0) | 2020.03.28 |