[英]How to use the str.translate() method from Python in objective c?
所以标题解释了大部分内容。 我开始研究iOS的Objective c,我还没有发现是否有一种方法可以使用translate() - 就像在Objective c中一样。
这是我在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);
输出:
th3s 3s str3ng 2x1mpl2 .... w4w !!!
就我而言,没有类似translate()
内置方法。 (但是,您可以通过使用PyObjc在Objective C中获得完全相同的功能,查找它)
您可以尝试使用replaceOccurrencesOfString:withString:options:range
NSMutableString上的replaceOccurrencesOfString:withString:options:range
或者自己编写一个函数,使用循环查看字符串中的每个字符,检查是否必须替换它,如果是,则将其替换为右侧字符。 (因为这就是translate()
函数所做的,对吧?)
纯C中的translates()
算法(inplace变量)是:
char *input; // input C string
for (char *s = input; *s; ++s)
*s = trantab[(unsigned char) *s];
trantab
可以从intab
, outtab
制作的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++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.