gpt4 book ai didi

用 C 计算数组中包含的字母字符

转载 作者:太空宇宙 更新时间:2023-11-04 00:56:14 24 4
gpt4 key购买 nike

我在做一道作业题时遇到了麻烦,我已经研究了很长时间了。我不确切地知道为什么会问这个问题,需要对此进行一些澄清,并插入正确的方向。

问题是:

(2) Solve this problem using one single subscripted array of counters. The program uses an array of characters defined using the C initialization feature. The program counts the number of each of the alphabetic characters a to z (only lower case characters are counted) and prints a report (in a neat table) of the number of occurrences of each lower case character found. Only print the counts for the letters that occur at least once. That is do not print a count if it is zero. DO NOT use a switch statement in your solution. NOTE: if x is of type char, x-‘a’ is the difference between the ASCII codes for the character in x and the character ‘a’. For example if x holds the character ‘c’ then x-‘a’ has the value 2, while if x holds the character ‘d’, then x-‘a’ has the value 3. Provide test results using the following string:

“This is an example of text for exercise (2).”

这是我到目前为止的源代码:

#include<stdio.h>

int main() {

char c[] = "This is an example of text for exercise (2).";
char d[26];

int i;
int j = 0;
int k;

j = 0;

//char s = 97;

for(i = 0; i < sizeof(c); i++) {
for(s = 'a'; s < 'z'; s++){
if( c[i] == s){

k++;
printf("%c,%d\n", s, k);
k = 0;

}
}
}
return 0;

}

如您所见,我当前的解决方案有点贫乏。感谢您的帮助,我知道网上的每个人都不一定喜欢帮助别人做作业。 ;P

最佳答案

char c[] = "This is an example of text for exercise (2).";
int d[26] = {0}, i, value;

for(i=0; i < sizeof(c) - 1; i++){ //-1 to exclude terminating NULL
value = c[i]-'a';
if(value < 26 && value >= 0) d[value]++;
}

for(i=0; i < 26; i++){
if(d[i]) printf("Alphabet-%c Count-%d\n", 'a'+i, d[i]);
}

已更正。感谢 caf 和 Leffler。

关于用 C 计算数组中包含的字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2399474/

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