从字符串中删除元音
NSMutableString *stringa = [[NSMutableString alloc] initWithFormat:@"%@", surnameField.text];
if ([stringa length] < 3) {
[stringa appendString:@"x"];
}
NSMutableString *consonanti = [[NSMutableString alloc] init];
NSCharacterSet *vocali = [NSCharacterSet characterSetWithCharactersInString:@"aeiouàèìòùáéíóúAEIOUÀÈÌÒÙÁÉÍÓÚ"];
NSRange r;
for (int i=0; i < [stringa length]; i++) {
r = [stringa rangeOfCharacterFromSet:vocali];
if (r.location != NSNotFound) {
[consonanti appendFormat:@"%c",[stringa characterAtIndex:i]];
}
else {
}
}
cfField.text = consonanti;
[stringa release];
[consonanti release];
cfField.text 的结果始终是带有元音的辅音,而结果必须仅为辅音。我不知道。
NSMutableString *stringa = [[NSMutableString alloc] initWithFormat:@"%@", surnameField.text];
if ([stringa length] < 3) {
[stringa appendString:@"x"];
}
NSMutableString *consonanti = [[NSMutableString alloc] init];
NSCharacterSet *vocali = [NSCharacterSet characterSetWithCharactersInString:@"aeiouàèìòùáéíóúAEIOUÀÈÌÒÙÁÉÍÓÚ"];
NSRange r;
for (int i=0; i < [stringa length]; i++) {
r = [stringa rangeOfCharacterFromSet:vocali];
if (r.location != NSNotFound) {
[consonanti appendFormat:@"%c",[stringa characterAtIndex:i]];
}
else {
}
}
cfField.text = consonanti;
[stringa release];
[consonanti release];
The result of cfField.text is always consonants with vowels, while the result must be only consonants. I don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将在循环的每次迭代中测试整个字符串中是否存在元音,因此您始终会依次添加每个字符。
在 for 循环中,您需要以下代码:
这会检查单个字符是否不在元音字符集中,并将其添加到可变字符串中。
You are testing for the presence of vowels in the whole string with each iteration of the loop, so you will always add each character in turn.
In your for loop, you need the following code instead:
This checks that the individual character is not in the vowel character set, and adds it to your mutable string.
请注意,如果您使用
characterAtIndex:
访问单个字符,组合字符将被分解为单个组件,例如变音符号。例如,Unicode 语言中的变音符号是一种重音符号,就像元音字符串中“é”中的重音符号一样。
更好的方法是在其组合字符上迭代字符串:
您将看到此代码片段清除了原始字符串中的基本元音和变音符号的组合字符。
Notice that if you use
characterAtIndex:
to access the individual characters, composed characters will be broken into their single components, such as a diacritical mark.A diacritical mark in Unicode-speak is for instance an accent, like the one in "é" in your string of vowels.
A better way is to iterate the string over its composed characters:
You will see that this snippet cleans the original string of composed characters for both the base vowel and the diacritical mark.
这也应该有效 - 首先通过使用它们作为字符串的分割字符来消除所有声音,然后再次连接所有收到的字符串部分:
我不知道性能如何,但它看起来很短:-)。
This should work too - first get rid of all vocals by using them as splitting characters for the string, then concatenate all received string parts again:
I don't know about the performance, but it looks short :-).
你可以尝试这样的事情:
You could try something like: