#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 []中的元素数量,然后它会找到多少次&#39; a&#39;发生在数组中。然后我需要找到&#39; a&#39;的索引。发现了。我只能找到第一个&#39; a&#39;之后它停止了。我该如何解决这个问题?
答案 0 :(得分:0)
此代码:
points(0,fun(0),pch=16)
points(Re(polyroot(c(4,3,2,1))[2]),0,pch=16)
仅查找第一个字母。您需要在循环中执行这些步骤:
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
是多余的。