tr-alike character replace function

M

Mik

Hi,

I need the functionality of Perl tr (or Unix tr command) in a C
function. I mean replacing each character of a list of characters with
the character in another counterpart list. For example:

char* str = "hello";
printf("original string: '%s'\n", str);
tr(str, "ho", "jy");
printf("transliterated string: '%s'\n", str);

Which must end up printing:

original string: 'hello'
transliterated string: 'jelly'

It would be great if it recognizes Perl regexp syntax like [A-Z], \d,
\s and so on, so calls like tr(str, "[eo]","-") make str = "h-ll-".

Does anybody know if there is a public library which implements this
functionality?. I've looked at glib but can't find something similar.
 
M

Mik

I don't think that includes anything like tr (unless I missed it).

To the OP: why not look at tr itself?  The GNU port is part of the
coreutils package and you can browse the source at:

Thanks. I've taken up a glance at the code and seems too complex for
what I'm trying to do (it should be as optimized as possible because
it will be called around a trillion times). I like glib because you
can pre-compile the patterns in an optimized way, just like Perl does.
I don't know why such a function is not included in glib as I find it
very handy.

So probably I will end up writing myself some ad-hoc function to do
the task. I'm trying to avoid the O(n^2) complexity of looking at each
char of the input string, and for each one then look each char of the
translation string. What I'm trying to do is to translate some special
Spanish accented characters into the equivalent upper-cased ASCII-7,
for example:

"áéíóú" becomes "AEIOU"

As the character range is really small (256 elements, we use Latin1
encoding here) an ASCII-indexed vector will do it quick'n'simple. Too
bad it depends on the current encoding being Latin1 and doesn't
support fancy character classes, but it will work so far...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top