gpt4 book ai didi

c - 查找数组中字符 'a'的索引

转载 作者:行者123 更新时间:2023-11-30 17:08:43 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h.>


int main()
{
char hurray[] = "Hooray for all of us"; //Character String
char *hurrayptr = hurray; //Pinter to array hurray
int i = 0; //Used in for loop to display position and character
int d = 0; //Used in printf statement to count the position
int k;
int count = 0;
int index;
int f = 0;

printf("\tPosition\t Character");

while (hurray[i] > 20) {

for (i = 0; i < 20; i++) {

printf("\n\t hurray[%d]\t\t %c", d++, *hurrayptr++);

}
}

for (k = 0; hurray[k]!= '\0'; k++)
if ('a' == hurray[k]) { //specifies character 'a' is to be counted

count++;
}
printf("\n'A' occurs %d times in this array\n", count);

hurrayptr = strchr(hurray, 'a');
index = (int)(hurrayptr - hurray);
f++;

printf("The letter 'a' was find in hurray[%d]\n", index);

return 0;
}

我试图让它显示数组 hurray[] 中的元素数量,然后查找数组中“a”出现的次数。然后我需要找到找到的“a”的索引。我只能让它找到第一个“a”,然后它就停止了。我该如何解决这个问题?

最佳答案

这段代码:

hurrayptr = strchr(hurray, 'a');
index = (int)(hurrayptr - hurray);
f++;

printf("The letter 'a' was find in hurray[%d]\n", index);

仅查找第一个字母。您需要循环执行这些步骤:

hurrayptr = strchr(hurray, 'a');
do {
index = (int)(hurrayptr - hurray);
printf("The letter 'a' was find in hurray[%d]\n", index);
hurrayptr = strchr(hurrayptr+1, 'a');
} while (hurrayptr);

strchr 的第一次调用从字符串的开头开始,循环内部的调用开始查找找到的最后一个实例。

此外,这不是必需的:

while (hurray[i] > 20) {

您有一个 for 循环,它已经打印了所有字符。 while 是多余的。

关于c - 查找数组中字符 'a'的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33554731/

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