我有一个NSString
或者NSMutableString
想要获得特定角色的出现次数.
我需要为很多字符做这个 - 在这种情况下是大写的英文字符 - 所以它很快就会很好.
您可以在一行中执行此操作.例如,这会计算空格数:
NSUInteger numberOfOccurrences = [[yourString componentsSeparatedByString:@" "] count] - 1;
在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倍.
replaceOccurrencesOfString:withString:options:range:
将返回a中替换的字符数NSMutableString
.
[string replaceOccurrencesOfString:@"A" withString:@"B" options:NSLiteralSearch range:NSMakeRange(0, [receiver length])];
无论何时在寻找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];
现在,我想到的第一件事就是: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