maketrans and translate
bearophile
bearophileHUGS at lycos.com
Mon Feb 13 05:09:06 PST 2012
Stewart Gordon:
> Use an associative array for the translation table.
A new version of the code:
import std.stdio, std.string, std.range;
void main() {
char[] text = "dssdadsdasdas".dup; // lots of MBs of pure 7 bit ASCII text
dchar[dchar] aa = ['A':'5', 'a':'5', 'B':'7', 'b':'7', 'C':'6', 'c':'6',
'D':'3', 'd':'3', 'E':'0', 'e':'0', 'F':'4', 'f':'4', 'G':'9', 'g':'9',
'H':'9', 'h':'9', 'I':'6', 'i':'6', 'J':'1', 'j':'1', 'K':'7', 'k':'7',
'L':'8', 'l':'8', 'M':'5', 'm':'5', 'N':'1', 'n':'1', 'O':'8', 'o':'8',
'P':'8', 'p':'8', 'Q':'1', 'q':'1', 'R':'2', 'r':'2', 'S':'3', 's':'3',
'T':'4', 't':'4', 'U':'7', 'u':'7', 'V':'6', 'v':'6', 'W':'2', 'w':'2',
'X':'2', 'x':'2', 'Y':'3', 'y':'3', 'Z':'9', 'z':'9'];
auto text3 = text.translate(aa, "\"");
writeln(text3);
}
> Or write your own functions that work in the same way as maketrans/translate.
The code with the associative array is longer, and every char in the original string requires one or two associative array lookups. This is quite inefficient for ASCII strings.
Instead of writing my own string functions, or copying them from an older Phobos, what about the idea of keeping both the old maketrans and translate functions too and to un-deprecate them (maybe moving them in std.ascii)? They are not UTF-safe, but I have large amounts of biological data text that is not Unicode.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list