gpt4 book ai didi

ios - 如何计算字符串中所有字符的出现次数?

转载 作者:行者123 更新时间:2023-11-28 20:01:51 25 4
gpt4 key购买 nike

我正在尝试查找字符串中每个字符的使用次数。例如,在字符串“wow”中,我想计算字符“w”的使用次数和字符“o”的使用次数。然后我想将这些字符添加到 NSMutableArray。有没有一种编程方式来计算所有特定字符的使用次数?获取 NSString 中所有字符出现的次数?还是我必须分别计算每个字符出现的次数?

最佳答案

参见 iOS - Most efficient way to find word occurrence count in a string

NSString     *string     = @"wow";
NSCountedSet *countedSet = [NSCountedSet new];

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
options:NSStringEnumerationByComposedCharacterSequences | NSStringEnumerationLocalized
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){

// This block is called once for each word in the string.
[countedSet addObject:substring];

// If you want to ignore case, so that "this" and "This"
// are counted the same, use this line instead to convert
// each word to lowercase first:
// [countedSet addObject:[substring lowercaseString]];
}];

NSLog(@"%@", countedSet);
NSLog(@"%@", [countedSet allObjects]);
NSLog(@"%d", [countedSet countForObject:@"w"]);

关于ios - 如何计算字符串中所有字符的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23668704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com