2015-11-19 76 views
0

我正在練習一維數組,並且問題來自用戶要求輸入一行文本,然後輸入用戶想要搜索的單詞並找出它在文本行中重複了多少次。它不一定是由空格分隔,可以是一個字(即'去'在'守門員')。在cstring文本中搜索單詞(一維數組/ C++)

我的問題是創建一個合適的如果條件在循環中搜索句子。事情是,我行變量是焦炭char line[200];),而我的字變量是string word;),所以,當我寫在循環的條件就這樣我的計劃給了我一個錯誤:

if (line[i] == word) 

然後我試着改變這個單詞變量爲char,並創建了一個循環來獲得輸入,但後來我陷入瞭如何計算循環來搜索文本行。

我只是想要一些指針。這是我的當前代碼迄今(它是一片混亂):

#include <iostream> 
#include <string> 
#include <cstring> 
using namespace std; 
int main() 

{ 
    char liner[200], word[200]; 
    int i, counter1 = 0, counter2 = 0; 


    cout<<"Enter a line of text: "; 
    cin.get (liner, 200); 

    cout<<"Enter a word to search: "; 

    for (i = 0; word[i] != ' '; i++) 
    { 
     cin>>word[i]; 

    } 

    cout<<endl; 

    for (i = 0; i < 200; i++) 
    { 
     if (liner[i] == word[t]) 
      { 
       counter2++; 
      } 

    } 

    cout<<word<<" was found "<<counter2<<" times."<<endl; 

    return 0; 
} 

回答

0

一種可能的解決方案是使用STRNCMP,其比較兩個字符串最多爲指定的長度,以查看它們是否相等(停止時的端要麼是或者已經比較了字符的數量)。

因此,代碼將是這樣的:

int main() 
{ 
    char liner[200], word[200]; 
    int i, counter1 = 0, counter2 = 0; 

    cout<<"Enter a line of text: "; 
    cin.getline(liner, 200); 

    cout<<"Enter a word to search: "; 
    cin.getline(word, 200); 
    cout<<endl; 

    int lineLen = strlen(line); 
    int wordLen = strlen(word); 

    for (i = 0; i < lineLen && I < wordLen; i++) 
    { 
     if (strncmp(&line[i], word, wordLen) 
     { 
      counter2++; 
     } 
    } 

    cout<<word<<" was found "<<counter2<<" times."<<endl; 

    return 0; 
} 

改進方案,你可以嘗試不使用固定大小的數組,但將數據讀入一個std ::字符串。

+0

'strstr'也是有用的... – Deduplicator

+0

@Deduplicator你應該張貼作爲答案,因爲它是正確的。 –