我试图找出字符串中每个字符被使用的次数。例如,在字符串"wow“中,我想计算字符"w”被使用的次数和字符"o“被使用的次数。然后,我想将这些字符添加到NSMutableArray中。有没有一种编程的方法来计算所有特定字符被使用的次数?获取NSString中所有字符的出现次数?或者我必须分别计算每个字符的出现次数?
发布于 2014-05-15 12:12:03
请参阅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"]);发布于 2014-05-15 11:48:42
确切的答案取决于一些问题-
假设您只想计算8位,a-z独立于大小写,您可以使用类似于-
- (NSArray *)countCharactersInString:(NSString *)inputString
{
NSMutableArray *result=[[NSMutableArray alloc]initWithCapacity:26];
for (int i=0;i<26;i++) {
[result addObject:[NSNumber numberWithInt:0]];
}
for (int i=0;i<[inputString length];i++)
{
unichar c=[inputString characterAtIndex:i];
c=tolower(c);
if (isalpha(c))
{
int index=c-'a';
NSNumber *count=[result objectAtIndex:index];
[result setObject:[NSNumber numberWithInt:[count intValue]+1] atIndexedSubscript:index];
}
}
return (result);
}另一种方法是使用NSCountedSet -它处理所有字符截断等,但将是“稀疏的”-没有字符串中不存在的字符的条目。另外,下面的实现是区分大小写的- w不同于w。
- (NSCountedSet *)countCharactersInString:(NSString *)inputString
{
NSCountedSet *result=[[NSCountedSet alloc]init];
for (int i=0;i<[inputString length];i++)
{
NSString *c=[inputString substringWithRange:NSMakeRange(i,1)];
[result addObject:c];
}
return result;
}发布于 2016-06-30 02:06:49
NSString *str = @"Program to Find the Frequency of Characters in a String";
NSMutableDictionary *frequencies = [[NSMutableDictionary alloc]initWithCapacity:52];initWithCapacity:52 -容量可以更多取决于字符集(目前: a-z,A-Z)
for (short i=0; i< [str length]; i++){
short index = [str characterAtIndex:i];
NSString *key = [NSString stringWithFormat:@"%d",index];
NSNumber *value = @1;
short frequencyCount=0;
if ([frequencies count] > 0 && [frequencies valueForKey:key]){
frequencyCount = [[frequencies valueForKey:key] shortValue];
frequencyCount++;
value = [NSNumber numberWithShort:frequencyCount];
[frequencies setValue:value forKey:key];
}
else{
[frequencies setValue:value forKey:key];
}
}显示字符串中每个字符的匹配项
[frequencies enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *ky = (NSString*)key;
NSNumber *value = (NSNumber*)obj;
NSLog(@"%c\t%d", ([ky intValue]), [value shortValue]);
}];https://stackoverflow.com/questions/23668704
复制相似问题