当前位置:  开发笔记 > IOS > 正文

NSString中字符的出现次数

如何解决《NSString中字符的出现次数》经验,为你挑选了5个好方法。

我有一个NSString或者NSMutableString想要获得特定角色的出现次数.

我需要为很多字符做这个 - 在这种情况下是大写的英文字符 - 所以它很快就会很好.



1> gbaor..:

您可以在一行中执行此操作.例如,这会计算空格数:

NSUInteger numberOfOccurrences = [[yourString componentsSeparatedByString:@" "] count] - 1;


虽然创建一个临时数组..为了速度,[Jacque的答案](http://stackoverflow.com/a/15947190/482601)应该是首选.

2> Jacque..:

在NSString上尝试此类别:

@implementation NSString (OccurrenceCount)

- (NSUInteger)occurrenceCountOfCharacter:(UniChar)character
{
    CFStringRef selfAsCFStr = (__bridge CFStringRef)self;

    CFStringInlineBuffer inlineBuffer;
    CFIndex length = CFStringGetLength(selfAsCFStr);
    CFStringInitInlineBuffer(selfAsCFStr, &inlineBuffer, CFRangeMake(0, length));

    NSUInteger counter = 0;

    for (CFIndex i = 0; i < length; i++) {
        UniChar c = CFStringGetCharacterFromInlineBuffer(&inlineBuffer, i);
        if (c == character) counter += 1;
    }

    return counter;
}

@end

这个componentsSeparatedByString:方法比方法快约5倍.



3> CynicismRisi..:

replaceOccurrencesOfString:withString:options:range:将返回a中替换的字符数NSMutableString.

[string replaceOccurrencesOfString:@"A" 
                        withString:@"B" 
                           options:NSLiteralSearch 
                             range:NSMakeRange(0, [receiver length])];



4> Abizern..:

无论何时在寻找a中的东西NSString,请先尝试使用NSScanner.

NSString *yourString = @"ABCCDEDRFFED"; // For example
NSScanner *scanner = [NSScanner scannerWithString:yourString];

NSCharacterSet *charactersToCount = [NSCharacterSet characterSetWithCharactersInString:@"C"]; // For example
NSString *charactersFromString;

if (!([scanner scanCharactersFromSet:charactersToCount 
                          intoString:&charactersFromString])) {
    // No characters found
    NSLog(@"No characters found");
}

// should return 2 for this
NSInteger characterCount = [charactersFromString length];


您可以使用`nil`作为`skipSet`来调用`setCharactersToBeSkipped:(NSCharacterSet*)skipSet`,并且`NSScanner`不会跳过任何字符.
@lawrence默认情况下,NSScanner会忽略空格和空格.

5> VikingoS say..:

现在,我想到的第一件事就是:NSCountedSet

NSString *string = @"AAATTC";

NSMutableArray *array = [NSMutableArray array];

[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
    [array addObject:substring];
}] ;
NSCountedSet * set = [[NSCountedSet alloc] initWithArray:array];

for (NSString *nucleobase in @[@"C", @"G", @"A", @"T"]){
    NSUInteger count = [set countForObject:nucleobase];
    NSLog(@"%@: %lu", nucleobase, (unsigned long)count);
}

日志:

C: 1
G: 0
A: 3
T: 2

推荐阅读
mobiledu2402851203
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有