作者cacaliang (caca)
看板C_and_CPP
标题[问题] 文章内搜寻字串
时间Sun Mar 29 22:03:31 2009
想要在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