2011-10-28 55 views
1
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的結果始終與元音相輔相成,而結果必須僅爲輔音。我不知道。刪除字符串中的元音

+0

你到底想幹什麼?從字符串中刪除元音? – jrturton

+0

是的,正好... – Mario

+0

確切的重複http://stackoverflow.com/questions/7859683/objective-c-find-consonants-in-string –

回答

3

您正在測試整個字符串中是否存在元音,每次迭代循環時都會添加,因此您總是會依次添加每個字符。

在你的循環,你需要下面的代碼來代替:

if(![vocali characterIsMember:[stringa characterAtIndex:i]]) 
    [consonanti appendFormat:@"%C",[stringa characterAtIndex:i]]; 

這就驗證了個性不是元音字符集,並將其添加到您的可變的字符串。

+0

非常多,工作! – Mario

+0

@Mario必須接受此答案我希望 – swiftBoy

+2

'%c'是單個C'char'的格式說明符。你必須使用'%C'來創建一個'unichar'。 –

1

請注意,如果您使用characterAtIndex:訪問單個字符,則組合字符將被分解爲其單個組件,例如變音標記。

Unicode-speak中的變音符號例如是重音,就像您的元音字符串中的「é」中的一個。

一個更好的辦法是在其組成字符遍歷字符串:

// A string with composed diacritic characters 
// In clear text it is "Renée Ångström" 
NSString *stringWithComposedChars = @"Rene\u0301e A\u030Angstro\u0308m"; 
NSString *vowels = @"aeiouàèìòùáéíóúäëïöü"; 

NSMutableString *consonants = [NSMutableString string]; 

[stringWithComposedChars 
enumerateSubstringsInRange:NSMakeRange(0,[stringWithComposedChars length]) 
             options:NSStringEnumerationByComposedCharacterSequences 
             usingBlock: ^(NSString *substring,NSRange rng1, NSRange rng2, BOOL *stop) 
{ 
    if ([vowels rangeOfString:substring options:NSCaseInsensitiveSearch|NSWidthInsensitiveSearch].location == NSNotFound) { 
     [consonants appendString:substring]; 
    } 
}]; 

NSLog(@"Original string: \"%@\" - Vowels removed: \"%@\"", stringWithComposedChars, consonants); 

你會看到這個片段清除的字符組成的原始字符串爲基本元音和變音記號兩者。

0

這應該工作了 - 首先用它們作爲字符串分割字符擺脫所有唱腔,然後再串聯所有接收到的字符串部分:

NSArray* onlyConsonantsArray = [stringa componentsSeparatedByCharactersInSet:vocali]; 
NSString* onlyConsonantsString = [onlyConsonantsArray componentsJoinedByString: @""]; 

我不知道性能,但它看起來很短:-)。

0

你可以嘗試這樣的:

-(NSString *) removeVowels:(NSString *) value 
    { 
     NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([A,Á,Ã,E,É,Ê,I,Í,O,Ô,Ó,Õ,U,Û,Ü,Ú]?)" options:NSRegularExpressionCaseInsensitive error:nil]; 
     return [regex stringByReplacingMatchesInString:value options:0 range:NSMakeRange(0, [value length]) withTemplate:@""]; 
    }