Naming Conventions |
|||||
|
Scalar |
Vector |
Matrix |
Any |
Non- |
Boolean |
BS |
BV |
BM |
BA |
BN |
Integer |
IS |
IV |
IM |
IA |
IN |
Float |
FS |
FV |
FM |
FA |
FN |
Numeric |
NS |
NV |
NM |
NA |
NN |
Character |
CS |
CV |
CM |
CA |
CN |
Enclosed |
ES |
EV |
EM |
EA |
EN |
enclosed |
TS |
TV |
TM |
TA |
TN |
Simple |
SS |
SV |
SM |
SA |
SN |
Any |
AS |
AV |
AM |
AA |
AN |
phrase e.g.: .X...Y. ⍝ X←BS; Y←IV |
|||||
combinations: use ISV for Integer scalar∨vector |
|||||
B3, I4 &c. to specify higher ranks. |
|||||
ReplaceCharactersInString
Given a character vector V and a translate table consisting of two equal length character vectors T and S, replace all occurrencies in V of characters also in T with the corresponding character from S.
(S,V)[(T,V)⍳V] ⍝ V←CV; S←CV; T←CV; (⍴S)=⍴T
There are many ways of coding this some of which will be quicker in some APLs. The advantage here is that it is concise, memorable and returns a result directly rather than as a side effect.
Examples
⎕FX⍕2 1⍴'r←tv ReplaceCharsInString cv' 'r←((1⊃tv),cv)[((0⊃tv),cv)⍳cv]'
'papa' 'lima'ReplaceCharsInString 'alpha papa lima'
illhi lili limi
'one' 'two'ReplaceCharsInString'zero one two three four five'
zort two twt throo ftur fivo
'two' 'one'ReplaceCharsInString'zero one two three four five'
zere ene one ohree feur five
Conforming Variants
As square bracket indexing[] is deprecated in some quarters I give here a version that takes the same number of characters and about the same execution time that uses the index function ⌷ instead:
(⊂(T,V)⍳V)⌷S,V
and another that uses pick ⊃ that's one character longer and perhaps marginally quicker:
((T,V)⍳V)⊃¨⊂S,V
All three variants can be enhanced by the doubling of the commas in the phrase to be rank independent in the text to be changed.
⎕FX⍕2 1⍴'r←tv ReplaceCharsInArray ca' 'r←(((0⊃tv),,ca)⍳ca)⊃¨⊂(1⊃tv),,ca'
nums,'one' 'two' ReplaceCharsInArray' ',nums←2 3 5⍴'zero one two threefour five '
zero zort
one two
two twt
three throo
four ftur
five fivoThere is many a related phrase which is speedier for the special case of a single replacement character. Here is one that is similarly direct which again could be specified using any if the three indexing techniques:
(S,V)[1+(T≠V)×⍳⍴V]
Compatibility
Checked with: APL2, Dyalog, NARS2000, APLX
Test Cases
Show test cases
Test my code, both Examples and Test Cases.
See also: ...
Mentor: PhilLast
Tags: <AppropriateCamelCaseName> <Simpleword>
APL Wiki