如何计算字符串中每个字母(忽略大小写)中c的出现次数?因此它会打印出来letter: # number of occurences,我有代码来计算一个字母的出现次数,但是如何计算字符串中每个字母的出现次数呢?
{
char
int count = 0;
int i;
//int length = strlen(string);
for (i = 0; i < 20; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
输出:
a : 1
b : 0
c : 2
etc...
Run Code Online (Sandbox Code Playgroud)
小智 8
假设您有一个char8位的系统,并且您尝试计算的所有字符都使用非负数进行编码.在这种情况下,您可以写:
const char *str = "The quick brown fox jumped over the lazy dog.";
int counts[256] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
counts[(int)(str[i])]++;
}
for (i = 0; i < 256; i++) {
printf("The %d. character has %d occurrences.\n", i, counts[i]);
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将计算字符串中的所有字符.如果你100%绝对肯定你的字符串里面只有字母(没有数字,没有空格,没有标点符号),那么1.要求"不区分大小写"开始有意义,2.你可以减少条目数到英文字母中的字符数(即26),你可以这样写:
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";
int counts[26] = { 0 };
int i;
size_t len = strlen(str);
for (i = 0; i < len; i++) {
// Just in order that we don't shout ourselves in the foot
char c = str[i];
if (!isalpha(c)) continue;
counts[(int)(tolower(c) - 'a')]++;
}
for (i = 0; i < 26; i++) {
printf("'%c' has %2d occurrences.\n", i + 'a', counts[i]);
}
Run Code Online (Sandbox Code Playgroud)