[問題] 文章內搜尋字串

看板C_and_CPP作者 (caca)時間15年前 (2009/03/29 22:03), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/3 (看更多)
想要在txt檔,文章字數不定的文章中, 搜尋一個字串,並看它出現幾次。 目前我幼兒般的程度只有辦法寫成這樣~ #include <iostream> #include <fstream> using namespace std; int main() { ifstream infile; infile.open("article.txt"); int Maxlength = 100; string a[Maxlength]; string b; int flag=0; int counter=0; for(int j=0;j<Maxlength;j++) infile>>a[j]; cout<<"enter a string :"; cin>>b; for(int i=0;i<Maxlength;i++) { if(a[i]==b) { flag=1; counter++; } else continue; } if(flag==1) cout<<"found,and this string had appeared "<<counter<<" times"; else cout<<"notfound"; infile.close(); return 0; } 但是如此一來,除非先知道文章長度,不然就會浪費變數。 有沒有辦法存一個比對一個, 也就是當 a(檔案中字串) 跟 b(要尋找之字串) 比完一次, a再去txt檔中讀取下一個字串,把原先的蓋過去,然後再去跟b比 這樣即使不用預先知道文章長度~也可以比較。 還有一個問題~如果遇到標點符號的前一個字串,用此方法就不能辨識。 有沒有什麼好方法可以克服呢? 剛初學不久~如果有考慮不周~還請各位指導 感謝~~ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.115.241.211
文章代碼(AID): #19pt-q4M (C_and_CPP)
文章代碼(AID): #19pt-q4M (C_and_CPP)