如何统计一个文本文件里一个特定字符串出现了多少次?请给出实例代码,谢谢谢谢!!!
解决方案 »
- 请问在openGL中怎么取得鼠标当前位置的坐标
- 紧急求助@@@@@@@@@
- 为何会出现这样的编译通不过问题:fatal error C1010: unexpected end of file while looking for precompiled header directive
- 在vc里,如何模拟键盘操作,通过模拟“ctrl+V”,把剪切板的内容copy到页面。
- 特别是服务器都需要支持许多不同的编码吗?
- 用VC怎么做程序的升级啊?
- 请问:谁知道double类型的数据如何表示成二进制?如果谁有IEEE754标准,麻烦给我一份!
- 关于CInternetSession的问题
- 如何修改控件
- 想要成为一名VC++合格的程序人员应该具有那些知识?
- 如何在ado中使用连接池
- 如何用VC++写一个C语言编辑器(满分送上)
while(文件没有读完)
{
if(readed==xxx)
count++;
}
{
读一段
strcmp
}
int nNumsStrings = 0;
int nNumCompare = 0;
从文件头开始,找到第一个跟字符串相等的字符,
nNumCompare ++;
比较第二个;还是相等 nNumCompare ++;
如果nNumCompare ==nLength 或者 出现不等了
{
说明没有找到;
nNumCompare = 0;
}else
{
nNumsStrings ++;
nNumCompare =0;
}大致思路肯定是正确的,至于循环你自己考虑,应该很简单的.
if(nNumCompare ==nLength)
{
// 找到
nNumsStrings ++;
nNumCompare =0;
}else
{
if(出现不等的)
{
// 没有找到,重新标记
...
}
}
i = body.find("yourstring");
while(i!=-1)
{
body = body.right(body.getlength()-i);
i = body.find("yourstring");
index++;
}
CFile file;
file.Open("FileName",CFile::modeRead | CFile::typeBinary);
int length = file.GetLength();
VERIFY(length > 0);
char *pStrBuffer = new char[length];// source string
file.Read(pStrBuffer,length);
file.Close();
char str2find[] = "ok";// string to find
char *pDest = NULL;
int count = 0, pos = 0;
while(pos < length)
{
pDest = strstr(pStrBuffer + pos,str2find);
if(pDest == NULL)
break;
else
{
pos = pDest - pStrBuffer + 1;
count++;//这是字符串出现的次数
}
}
delete pStrBuffer;
#include <iostream>
#include <fstream>
#include <string>using namespace std;
const std::string Key = "wo";int main(int argc, char* argv[])
{
if (argc >= 2)
{
std::ifstream ifile(argv[1]);
if (ifile.is_open())
{
int n = 0;
std::string str;
while(ifile >> str)
{
for(int k=0; (k=str.find(Key,k))!=std::string::npos; k++)
{
n++;
}
}
std::cout << "关键字有 : " << n << std::endl;
}
}
else
{
std::cout << "No file for open !" << endl;
}
return 0;
}
测试文件:
wo, wo, wo, and to bo ok wwe wo
mm oo m wo wowo and wowowk wookwokwo.
wwo kkwo kkwkwkowo搜索关键字: wo输出:15
用MFC和C++的思路一样。可以自己写一下,我也可以帮你写。
if (dlg.DoModal() == IDOK)
{
CString strFile = dlg.GetPathName();
CStdioFile file(strFile, CFile::modeRead);
CString strTxt;
CString strKey = "wo";
int n = 0;
while (file.ReadString(strTxt))
{
for(int k=0; (k=strTxt.Find(strKey, k))!=-1; k++)
{
n++;
}
}
TRACE("***** Wo Count : %d", n);
}
wo, wo, wo, and to bo ok wwe wo
mm oo m wo wowo and wowowk wookwokwo.
wwo kkwo kkwkwkowo搜索关键字: wo输出:15主要代码:
CStdioFile file(strFile, CFile::modeRead);
CString strTxt;
CString strKey = "wo"; //关键字
int n = 0; //统计个数while (file.ReadString(strTxt))
{
for(int k=0; (k=strTxt.Find(strKey, k))!=-1; k++)
{
n++;
}
}