trim ()이 char 160을 제거하지 않는 이유는 무엇입니까?
On 1월 31, 2021 by admin PicklistEntry
의 레이블에 문자 160 (분할 공백 없음)이 포함 된 시나리오가 있습니다. 값의 끝. 따라서 pe.label.getChars()
를 호출 할 때 배열 출력은 다음 문자입니다. (104, 101, 108, 108, 111, 160)
.
다음에 getChars()
, 후행 160 문자가 제거 될 것으로 예상합니다. 그러나 그렇지 않습니다. char 32를 사용하면 trim()
가 올바르게 제거합니다.
또한 normalizeSpace()
를 사용하면 char 160이 제거됩니다. .
내 주요 질문은 “trim()
가이 문자를 제거하지 않는 반면 normalizeSpace()
는 제거하는 이유입니다.
아래 코드 예를 참조하세요.
// get "hello " from character array using 160 for space String hello = String.fromCharArray(new Integer[] { 104, 101, 108, 108, 111, 160 }); System.debug("==>" + hello.trim()); //output ==> "hello " // get "hello " from character array using 32 for space hello = String.fromCharArray(new Integer[] { 104, 101, 108, 108, 111, 32 }); System.debug("==>" + hello.trim()); //output ==> "hello" // get "hello " from character array using 160 for space and call normalizeSpace() hello = String.fromCharArray(new Integer[] { 104, 101, 108, 108, 111, 160 }); System.debug("==>" + hello.normalizeSpace()); //output ==> "hello"
수정 또한 normalizeSpace()
를 호출 할 때 char 160은 실제로 char 32로 변환됩니다. 따라서 160과 추가 32를 완전히 자르려면
String hello = String.fromCharArray(new Integer[] { 104, 101, 108, 108, 111, 160 }); String normalized = hello.normalizeSpace(); System.debug("==>" + normalized); //output ==> "hello" System.debug("==>" + normalized.getChars()); //output ==> (104, 101, 108, 108, 111, 32)
답변
문서 는 다음과 같이 말합니다.
탭 및 줄 바꿈 문자와 같은 선행 및 후행 ASCII 제어 문자는 다음과 같습니다. 문장의 시작이나 끝에없는 공백과 제어 문자는 제거되지 않습니다.
문자 그대로 공백 (ASCII 32), 탭 (ASCII 9), 줄 바꿈 (ASCII 10) 및 캐리지 리턴 (ASCII 13) 만 제거됩니다. 끊기지 않는 공백, 제로 너비 공백 등과 같은 다른 공백은 영향을받지 않습니다. 아마도 trim은 Apex의 시작으로 거슬러 올라가는 아주 오래된 방법이고 normalizeWhitespace는 상대적으로 새로운 방법이기 때문일 것입니다.
무엇을해야하는 빠른 대안입니다. 원하는 항목 :
// get " hello " from character array using 160 for space String hello = String.fromCharArray(new Integer[] { 160, 104, 101, 108, 108, 111, 160 }); System.debug("==>"" + hello.replaceAll("^\\p{IsWhite_Space}+|\\p{IsWhite_Space}+$","")+"""); //output ==>"hello"
^\\p{IsWhite_Space}+|\\p{IsWhite_Space}+$
. ' 답변에 예제를 포함하겠습니다.