簡體   English   中英

如何在目標c中使用Python中的str.translate()方法?

[英]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可以從intabouttab制作的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM