2012-03-12 28 views
1

我對C很新穎,我想我會嘗試製作一個解析字符串輸入以揭示真實單詞的程序,並讓它工作,但有些單詞會得到意想不到的結果。下面是正常工作的它的一個例子:在C中解讀字符串

輸入字:停止

匹配:選擇採用
比賽:後
比賽:盆
比賽:現貨
比賽:停止 比賽:上衣

我使用的是一個名爲「aspell」的程序獲得的單詞列表,它允許我創建一個完整的文件RDS。奇怪的是,當我輸入「測試」或「足球」這樣的單詞時,響應會帶回包含原本不存在於輸入單詞中的字母的單詞。我在這裏做錯了什麼?以下是我的解讀功能,它完成了大部分工作。另外,我會發布「足球」例如

int unscrambleWord(int fgLetters) { 

     // integer used for the counter 
     int i = 0; 

     // first make sure that the lengths of the word and of the list word is the same 
     if(strlen(currentLine) == strlen(input)) { 

       // loop through each letter in the word given 
       for(i = 0; i < strlen(input); i++) { 

         // search the line for the current letter, if we find it increment fgLetters 
         if(strchr(currentLine, input[i]) != NULL) 
           fgLetters++; 

       } // end for 

       // once we have finished looping through the word; evaluate fgLetters 
       if(fgLetters == strlen(input)) { 

         // fgLetters will be equal to the length of the word if each letter appears in the word 
         printf("\tMatch: %s \n", currentLine); 

       } // end if - evaluate length of fgLetters 

     } 

    // return the fgLetters after we have possibly incremented it 
     return fgLetters; 

} 

這裏是足球的例子:

Enter Word:football 

Match: blastoff 
Match: boastful 
Match: flatboat 
Match: football 
Match: lifeboat 
Match: softball 

出於某種原因,有s在這場比賽中的字符串,但似乎字符數是一樣。

回答

3

該算法給出誤報。

football這個詞的每個字母都在文字softball中。但這並不意味着你可以重新排列字母來改變這個詞。您將兩個o與相同的o字母匹配。

找到匹配的簡單方法是對信件進行排序,並看到您得到相同的單詞。

football -> abflloot 
softball -> abfllost 
+0

我喜歡你的算法。 – EricSchaefer 2012-03-12 21:05:30

+0

是的,這是一個好主意,我沒有想到! – 2012-03-12 21:07:42

1

您只檢查來自源的字母是否包含在當前行中,但不檢查當前行中是否有字母不在輸入中。您還需要處理多於一次的字母(在輸入和字詞列表中的行中)。

+0

這是我認爲最好解釋的答案,所以也許我需要兩次運行「for」循環,但切換輸入和currentLine變量? – 2012-03-12 21:03:31

+0

以及這是一個錯誤的答案..即使你會檢查你仍然可以得到誤報。 (例如:「goo」和「gog」)。檢查我的答案。 – 2012-03-12 21:03:45

+0

使用Karolys的答案。對輸入和當前行進行排序並進行比較。那樣做並不容易。 – EricSchaefer 2012-03-12 21:07:01

2

你可以讓重複的字母重複計算。例如,在football中有兩個'o'和'兩個'l,所以你允許s和u誇耀。

在C代碼中,一次抓取strlen的結果並在循環中使用它通常是明智的,而不是反覆調用它。只有最聰明的C編譯器纔會注意到strlen(word)在每次循環中都是相同的。