Articles
trim()がchar 160を削除しないのはなぜですか?
On 1月 31, 2021 by admin PicklistEntry
のラベルにchar160(改行なしスペース)が含まれているシナリオがあります。値の終わり。したがって、pe.label.getChars()
を呼び出すと、配列の出力は次の文字になります:(104, 101, 108, 108, 111, 160)
。
次にgetChars()
、末尾の160文字が削除されることを期待していますが、そうではありません。 char 32を使用すると、trim()
で正しく削除されます。
さらに、normalizeSpace()
を使用するとchar160が削除されます。 。
私の主な質問は、normalizeSpace()
が削除するのに、なぜtrim()
がこの文字を削除しないのかということです。
以下のコード例を参照してください。
// 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()
を呼び出すと、char160は実際にはchar32に変換されます。したがって、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}+$
。 '回答に例を含めます。