簡體   English   中英

如何計算NSString對象中非字母數字字符的數量?

[英]How can I count the number of non-alphanumeric characters in an NSString object?

我正在研究iOS開發,但我仍然對NSString對象很熟悉。 我現在需要計算字符串中非字母數字字符的數量。 我想出的一種方法是從字符串中剝離非字母數字字符,然后從原始字符串的長度中減去剝離后的字符串的長度,就像這樣...

NSCharacterSet *nonalphanumericchars = [[NSCharacterSet alphanumericCharacterSet ] invertedSet];

NSString *trimmedString = [originalString stringByTrimmingCharactersInSet:nonalphanumericchars];

NSInteger numberOfNonAlphanumericChars = [originalString length] - [trimmedString length];

但它不起作用。 計數始終為零。 如何計算NSString對象中非字母數字字符的數量?

非常感謝您的智慧!

方法的問題在於您沒有剝離字符,而是對其進行修剪。 這意味着僅從匹配集合的字符串的末尾剝離字符(中間什么都沒有)。

為此,您可以遍歷字符串並測試每個字符是否不是字母數字集的成員。 例如:

NSString* theString = // assume this exists
NSMutableCharacterSet* testCharSet = [[NSMutableCharacterSet alloc] init];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
NSUInteger length = [theString length];
NSUInteger totalNonAlnumCharacters = length;
for( NSUInteger i = 0; i < length; i++ ) {
  if( [testCharSet characterIsMember:[theString characterAtIndex:i]] )
    totalNonAlnumCharacters--;
}
NSLog(@"Number of non-alphanumeric characters in string: %lu", (long int)totalNonAlnumCharacters);
[testCharSet release];

既然您提到過您使用stringByTrimmingCharactersInSet:進行了嘗試,那么了解到實際上只有通過框架調用才能做到這一點可能會很有趣。 從Jason借用安裝代碼

NSString* theString = // assume this exists
NSMutableCharacterSet* testCharSet = [[NSMutableCharacterSet alloc] init];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
[testCharSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];

然后,您可以通過以下方式放棄for循環:

NSArray *nonComp = [theString componentsSeparatedByCharactersInSet:testCharSet];

它將在每個從字符集找到一個字符的索引處將字符串分開,從而創建剩余部分的數組。 然后,您可以使用鍵值編碼對所有片段的length屬性求和:

NSNumber *numberOfNonANChars = [nonComp valueForKeyPath:@"@sum.length"];

或者改為,將這些塊再次粘合在一起並計算長度:

NSUInteger nonANChars = [[nonComp componentsJoinedByString:@""] length];

但是:拆分組件將創建計數后不需要的數組和字符串-無意義的內存分配(componentJoindByString:也是如此)。 並使用valueForKeyPath:對於這種非常簡單的求和,似乎要比對原始字符串進行迭代要昂貴得多。

該代碼可能更面向對象,或者更不容易出錯,但是在兩種情況下,性能都將比Jason的代碼差幾個數量級。 因此,在這種情況下,良好的舊式for循環將使框架功能的使用率最高(因為使用的方法並非旨在用於此目的)。

NSString *str=@"str56we90";
int count;

for(int i=0;i<[str length];i++)
{
    int str1=(int)[str characterAtIndex:i];
    NSString *temp=[NSString stringWithFormat:@"%C",str1];

    if(str1 >96 && str1 <123  || str1 >64 && str1 <91)

        count=count +1;
}

int finalResult = [str length] - count;

計數將是您的最終結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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