简体   繁体   中英

How to use the str.translate() method from Python in objective c?

So the title explains most of it. I'm starting to work on Objective c for iOS and I haven't found out if there is a way to use a translate()-like in Objective c.

This is the program I've used for it in python.:

#!/usr/bin/python

from string import maketrans   # Required to call maketrans function.

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);

Output:

th3s 3s str3ng 2x1mpl2....w4w!!!

As far as I'm concerned, there is no builtin method for like translate() . (You could, however, get the exact same function in Objective C by using PyObjc, look it up)

You could try doing something with replaceOccurrencesOfString:withString:options:range on a NSMutableString or write a function yourself, with a loop that looks at every character in string, checks if it has to be replaced, and if so, replaces it with the right character. (Because that is what the translate() function does, right?)

translates() 's algorithm (an inplace variant) in pure C is:

char *input; // input C string

for (char *s = input; *s; ++s) 
  *s = trantab[(unsigned char) *s];

where trantab could be made from intab , outtab :

char trantab[256]; // translation table
for (int i = 0; i < 256; ++i)
  trantab[i] = i; // initialize

while (*intab && *outtab)
  trantab[(unsigned char) *intab++] = *outtab++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM