gpt4 book ai didi

使用函数(频率)计算字符数

转载 作者:行者123 更新时间:2023-11-30 14:57:39 28 4
gpt4 key购买 nike

尝试计算字符数并改进我的代码,我做了一些更改,而不是使用 while 循环。好奇是否有人对我如何改进我的代码以使其更专业且更便宜有任何建议?

#include <stdio.h>


int countingCharacters(char *message, int size, char charsToBeCounted);

int main()
{
char myString[] = "Hello World!";

int size = strlen(myString);

char charToBeCounted = 'a';
int i = 0;
int counter = 0;


while (myString[i] != '\0')
{
if (myString[i] == charToBeCounted)
{
counter++;
}
++i;
}

for (int i = 'a'; i <= 'z'; i++)
{
printf("%c: %d\n", charToBeCounted, countingCharacters(myString, size, charToBeCounted));
charToBeCounted++;
}
getchar();

return 0;
}

int countingCharacters(char *message, int size, char charsToBeCounted)
{
int counter = 0;

for (int i = 0; i < size; i++)
{
if (message[i] == charsToBeCounted)
counter++;
}

return counter;
}

最佳答案

整个事情你做了两次。首先在 main 中使用循环。

while (myString[i]!='\0'){...}

再次使用 countingCharacters 。浪费大量资源。

此外,如果您使用 strlen不要这样做while (myString[i]!='\0) 。将其替换为 for (i=0;i<size;i++) 。您投资寻找size然后不使用它。或者不要使用strlen就做while (myString[i]!='\0')

仅供引用:您可以使用'\0'0等价( \0 的整数值为 0 )。

关于使用函数(频率)计算字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43767208/

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