c++在txt文档中查找所有匹配的指定字符串,统计数量 和所在行数 用CString实现
时间: 2024-04-14 10:25:56 浏览: 25
如果你在使用 MFC(Microsoft Foundation Classes)框架,可以使用 CString 类来处理字符串和文本文件操作。下面是一个示例代码,用于在文本文件中查找所有匹配的指定字符串并统计数量以及所在行数:
```cpp
#include <iostream>
#include <fstream>
#include <afx.h>
int main() {
CStdioFile file;
CString filePath = _T("example.txt"); // 替换为你的文本文件路径
CString searchStr = _T("指定字符串"); // 替换为你要查找的字符串
if (file.Open(filePath, CFile::modeRead | CFile::typeText)) {
CString line;
int count = 0;
int lineNum = 0;
while (file.ReadString(line)) {
lineNum++;
int found = line.Find(searchStr);
while (found != -1) {
count++;
std::cout << "Found at line " << lineNum << ", position " << found << std::endl;
found = line.Find(searchStr, found + searchStr.GetLength());
}
}
std::cout << "Total occurrences: " << count << std::endl;
file.Close();
}
else {
std::cout << "Failed to open the file!" << std::endl;
}
return 0;
}
```
这段代码使用了 MFC 的 CStdioFile 类来打开和读取文本文件。它逐行读取文件内容,并在每一行中查找指定字符串的出现位置。如果找到匹配的字符串,将打印出所在行数和位置,并统计出现次数。
请确保在项目设置中正确添加了 MFC 支持,并链接了 MFC 库。
希望对你有所帮助!