Comment detail

文字変換表に基く文字列の変換 (Nested Flatten)

Squeak Smalltalk には #translateWith: というメソッドがあります。

引数として、通常は、あらかじめ用意した 256 文字のバイト文字列(もしくは、文字を要素とする配列など)をテーブルとして与えます。レシーバの文字列は、自らが含むバイト文字の ASCII コードの位置(正確にはそれ+1。Smalltalk の配列は1スタートなので…)の要素である文字と置き換えます。なお、同じく組み込みの String>>#asUppercase および #asLowercase という文字列の大文字、小文字化のためのメソッドは、この #translateWith: を上流で使用することで実現されています。

テーブルには、配列のほかに連想配列(Smalltalk では Python と同様に「辞書」と呼ぶ)を用いることもできるので、バイト文字の範囲外にも応用できます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
| table |
table := Character allByteCharacters.
'qwertyuiop' with: 'QWERTYUIOP' do: [:c1 :c2 | table at: c1 asciiValue + 1 put: c2].
'typewriter' translateWith: table   "=> 'TYPEWRITER' "

| table |
table := Character allByteCharacters.
($a to: $z) with: ($A to: $Z) do: [:c1 :c2 | table at: c1 asciiValue + 1 put: c2].
'typewriter' translateWith: table   "=> 'TYPEWRITER' "

| table |
table := Character allByteCharacters collect: [:char | char asUppercase].
'typewriter' translateWith: table   "=> 'TYPEWRITER' "

| table |
table := Dictionary new.
'qwertyuiop' with: 'qwertyuiop' do: [:c1 :c2 | table at: c1 asciiValue + 1 put: c2].
'typewriter' translateWith: table   "=> 'typewriter' "

Index

Feed

Other

Link

Pathtraq

loading...