2015-11-05 82 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