2015-11-05 85 views
0
#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'。我该如何解决?查找数组中的字符'a'的索引

+1

什么是'while(hurray [i]> 20){'试图做什么? – chux

+0

循环printf语句20次以显示数组中的字符及其索引 – bobblehead808

+0

您有语法错误。尝试将其编辑为可编译的第一个东西。 –

回答

0

此代码:

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是多余的。

+0

哦,好吧,这使得更有意义,谢谢! – bobblehead808