2016-12-12 37 views
0

我試圖編寫一個代碼,它將查找字符串中的特定單詞,並將其計入字符串中。 如果該字不存在於字符串中,則應打印該字未找到。 例如,對於句子「我遲到了」,對於「遲到」的結果應該是3字計數器代碼跳過

int count=0,i=0,j=0,k; 
char word[30]; 
getchar(); 
gets(word); 
k=strlen(word); 
while(arr[i]!='\0'){ 
    if(arr[i]==word[j]){ 
     i++; 
     j++; 
    } 
    i++; 
    if(arr[i]==' ') // moves across a word in the string 
     count++; // count a word the index has passed 
} 
if(j==k)   // if all letters were a match 
    printf("The word %s is placed in the %d place." , word , count); 
else 
    printf("The word %s is not found." , word); 
} 

的問題是,對每個句子中輸入,它打印:

字未找到%s。

我認爲它會跳過由於某種原因,第一部分,並直接進入word is not found,但即使是在調試後,爲什麼它會跳過我無法趕上當下和原因。

+1

歡迎來到Stack Overflow! [不要使用'gets()',這很危險](http://stackoverflow.com/q/1694036/2173917)。改用['fgets()'](https://linux.die.net/man/3/fgets)。 –

+0

你的代碼似乎在測試'word'中的字母是否出現在'arr'中的字母中 - 但不一定是連續的。這不是你想要的,所以除了代碼中的其他錯誤之外,你還有一個基本的邏輯錯誤。你的代碼似乎缺少一個內部循環。或者,您可以使用'strtok()'分隔空間,並使用'strcmp()'將'strtok()'返回的字符串與目標字詞進行比較。另外 - 注意@SouravGhosh的警告。 –

+0

使用調試器進行調試 – pm100

回答

1

請注意,i++出現兩次在主循環中,一次有條件地和一次無條件。它出現兩次的事實意味着當找到匹配的字母時,i增加兩次。您的代碼背後的意圖可以通過擺脫條件i++來實現。做出這樣的改變,擺脫getchar()(從我的觀點來看,這似乎毫無意義,因爲它只是放棄了輸入的第一個字母),並且用fgets產量不太理想的替代gets(將刪除的行註釋掉) :

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

int main(void){ 
    int count=0,i=0,j=0,k; 
    char * arr = "I am late"; 
    char word[30]; 
    //getchar(); 
    fgets(word,30,stdin); 
    strtok(word,"\n"); //trick for stripping off newline of nonempty line 
    k=strlen(word); 
    while(arr[i]!='\0'){ 
     if(arr[i]==word[j]){ 
      //i++; 
      j++; 
     } 
     i++; 
     if(arr[i]==' ') // moves across a word in the string 
      count++; // count a word the index has passed 
    } 

    if(j==k)   // if all letters were a match 
     printf("The word %s is placed in the %d place." , word , count); 
    else 
     printf("The word %s is not found." , word); 

    return 0; 
} 

當我運行它,並進入late我得到的結果是:

The word late is placed in the 2 place. 

這似乎是幾乎所有你想要的東西(有,如果你想數的差一錯誤3)。但是,不要慶祝得太早,因爲如果你輸入mate再次運行它,你得到:

The word mate is placed in the 2 place. 

你的代碼(一次固定這種方式)是,如果輸入單詞的字母順序顯示在真正測試arr,但不檢查這些字母是否彼此相鄰。你需要重新思考你的方法。

+0

另外,當兩個字母不匹配時,OP應該將j設置回0以避免第二個問題,您提到了關於按順序查找字母而不是連續查找的問題。 – Chimera

+0

最終我得到了我想要的結果,添加了一個條件,即單詞[j]!= EOF。感謝您的回答 – BellaconBud