【问题标题】:How to use the str.translate() method from Python in objective c?如何在目标 c 中使用 Python 中的 str.translate() 方法?
【发布时间】:2012-09-27 14:43:18
【问题描述】:

所以标题解释了大部分内容。我开始为 iOS 开发 Objective c,但我还没有发现是否有办法在 Objective c 中使用类似 translate() 的方法。

这是我在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!!!

【问题讨论】:

标签: python ios translate


【解决方案1】:

就我而言,没有像translate() 这样的内置方法。 (但是,您可以通过使用 PyObjc 在 Objective C 中获得完全相同的功能,请查阅)

您可以尝试在 NSMutableString 上使用 replaceOccurrencesOfString:withString:options:range 做一些事情,或者自己编写一个函数,使用一个循环查看字符串中的每个字符,检查是否需要替换它,如果需要,用正确的字符替换它. (因为这就是 translate() 函数的作用,对吧?)

【讨论】:

【解决方案2】:

translates() 在纯 C 中的算法(一个就地变体)是:

char *input; // input C string

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

其中trantab 可以由intabouttab 组成:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2023-03-07
    • 2011-04-29
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多