求助各位大虾:怎样指定文件中查找一个字符串并显示该字符串出现的次数,比如说在D:\tools\abc.txt文件中寻找bbc字符串出现的次数
。最好帮忙写个完整的程序,谢谢
|
http://www.programfan.com/club/image/arrow3.gif 回复内容 |
【XyRbj】:
用正则表达式去查找 这是最好的办法。
【todototry】:
统计文件的单词数
读文件的一行
int main()
{
ifstream infile;
string filename;
cout << "Please enter the file name: ";
cin >> filename;
infile.open(filename.c_str());
string line;
getline(infile, line, '\n');
infile.close();
vector wordsOfLine;
string::size_type pos = 0, prev_pos =0;
string word;
while ((pos = line.find_first_of(' ', pos)) != string::npos)
{
word = line.substr(prev_pos, pos - prev_pos);
prev_pos = ++pos;
wordsOfLine.push_back(word);
}
wordsOfLine.push_back(line.substr(prev_pos, pos - prev_pos));
size_t numOfLine = wordsOfLine.size();
cout << numOfLine << "words" << endl;
}
读整个文件的:
int main()
{
ifstream infile;
string filename;
cout << "Please enter the file name: ";
cin >> filename;
infile.open(filename.c_str());
string line;
vector wordsOfFile;
while (getline(infile, line, '\n'))
{
string::size_type pos = 0, prev_pos =0;
string word;
while ((pos = line.find_first_of(' ', pos)) != string::npos)
{
word = line.substr(prev_pos, pos - prev_pos);
prev_pos = ++pos;
wordsOfFile.push_back(word);
}
wordsOfFile.push_back(line.substr(prev_pos, pos - prev_pos));
}
| |