我想替换一些" ilegal"从字符串到另一个字符的字符" legal"字符,我有这个代码:
- (NSString *) quitarTildes:(NSString *)aStr
{
NSString *aux = aStr;
NSString *invalid = @"áéíóúÁÉÍÓÚñÑ";
NSString *valid = @"aeiouAEIOUnN";
for (int i = 0; i < [invalid length]; i++)
[aux stringByReplacingOccurrencesOfString: [NSString stringWithFormat:@"%c",[invalid characterAtIndex:i]]
withString: [NSString stringWithFormat:@"%c",[valid characterAtIndex:i]]];
NSLog(@"%@",aux);
return aux;
}
所有非法人物仍然存在......
NSString *test = @"Hólá, Ésto es una prueba.";
test = [self quitarTildes: test];
NSLog,回复:
2013-04-04 08:58:52.896 GeoRuta_v1[1960:907] Hólá, Ésto es una prueba.
答案 0 :(得分:2)
来自文档:
stringByReplacingOccurrencesOfString:withString:返回一个新字符串 其中所有出现的目标字符串都在接收器中 替换为另一个给定的字符串。
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
所以:
aux = [aux stringByReplacingOccurrencesOfString: [NSString stringWithFormat:@"%c",[invalid characterAtIndex:i]]
withString: [NSString stringWithFormat:@"%c",[valid characterAtIndex:i]]];
答案 1 :(得分:2)
实现目标的一个更简单的解决方案:
NSString *test = @"Hólá, Ésto es una prueba. - áéíóúÁÉÍÓÚñÑ";
test = [test stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:NULL];
NSLog(@"%@", test);
输出:
Hola, Esto es una prueba. - aeiouAEIOUnN
答案 2 :(得分:1)
一。您使用了characterAtIndex:
的错误格式说明符。该方法返回unichar
和不 char
(原因很明显)。您必须使用%C
(大写字母C)。
两个。您将返回原始字符串,而不是替换其字符。
NSMutableString *tmp = [aStr mutableCopy];
// ...
[tmp replaceOccurrencesOfString:[NSString stringWithFormat:@"%C", [invalid characterAtIndex:i]]
withString:[NSString stringWithFormat:@"%C", [valid characterAtIndex:i]]];