【发布时间】:2011-08-14 10:48:44
【问题描述】:
我编写了一个函数,可以将“›”、“«”等文本更改为符号“›”“«”,我想与 stackoverflow 用户分享这个函数。如果您有建议如何使此功能更好,请写下!!!谢谢!!!
- (NSString*) ChangeAccentsLettersToSymbols: (NSString*) strToCorrect {
NSLog(@"ChangeAccentsLettersToSymbols Entered\n");
static NSString * const codeMap[][2] = {
{@"¡", @"¡"}, {@"«", @"«"}, {@"»", @"»"}, {@"‹", @"‹"},
{@"›", @"›"}, {@"‚", @"‚"}, {@"„", @"„"}, {@"“", @"“"},
{@"”", @"”"}, {@"‘", @"‘"}, {@"’", @"’"}, {@"¢", @"¢"},
{@"£", @"£"}, {@"¥", @"¥"}, {@"€", @"€"}, {@"¤", @"¤"},
{@"ƒ", @"ƒ"}, {@">", @">"}, {@"<", @"<"}, {@"÷", @"÷"},
{@"°", @"°"}, {@"¬", @"¬"}, {@"±", @"±"}, {@"µ", @"µ"},
{@"&", @"&"}, {@"®", @"®"}, {@"©", @"©"}, {@"™", @"™"},
{@"•", @"•"}, {@"·", @"·"}, {@"§", @"§"}, {@"–", @"–"},
{@"—", @"—"}, {@"†", @"†"}, {@"‡", @"‡"}, {@"◊", @"◊"},
{@"↑", @"↑"}, {@"↓", @"↓"}, {@"←", @"←"}, {@"→", @"→"},
{@"↔", @"↔"}, {@"¿", @"¿"}, {@" ", @" "}, {@""", @"\""}
};
int count = sizeof(codeMap)/sizeof(codeMap[0]);
for( int i=0; i<count; ++i ) {
strToCorrect = [ strToCorrect stringByReplacingOccurrencesOfString: codeMap[i][0]
withString: codeMap[i][1] ];
}
for( int i=33; i<126; ++i) {
NSString* whotToReplace = [NSString stringWithFormat:@"&#%d;", i];
NSString* replaceWith = [NSString stringWithFormat:@"%c", (char*)i ];
strToCorrect = [strToCorrect stringByReplacingOccurrencesOfString: whotToReplace
withString: replaceWith ];
}
return strToCorrect;
}
【问题讨论】:
-
你可以用 NSDictionary 代替数组吗?
-
首先,Objective-C 中的方法名称按照约定以小写字符开头,就像在任何其他编程语言中一样(Visual BASIC、AFAIK 除外)。然后你想小写“‡”。接下来,
&#xxx;表示法可用于表示从 0 到 65535 (AFAIK) 的任何 UTF 字符,但您只涉及其中的一些字符,并且不处理八进制或十六进制。所以总而言之,这种方法确实很方便,但需要注意的是它并不完整,而且由于调用stringByReplacingOccurrencesOfString:withString:十几次,效率也很低。所以不要在长文本上使用它。 -
stringByReplacingOccurrencesOfString:withString: 我能做什么?
-
@Syed Absar:不,因为他的 C 数组是静态的,这意味着它将在 编译时 生成,并且与其他静态数据一起简单地映射到内存中.它也是最有效的迭代。使用 NSDictionary 会非常低效,而且要写很多东西。
-
@ViTo Brother:最有效的方法是使用状态机实现一个简单的解析器。当然,还有很多工作,但效率更高。对于短 HTML 文件,您的解决方案是可以接受的,但我不会向它扔 100kB 文件:-)