指定文件中查找一个字符串并显示该字符串出现的次数
来源:互联网 发布:c语言status 未声明 编辑:程序博客网 时间:2024/05/21 04:26
以下转自:http://bbs.csdn.net/topics/110120343
#include "iostream"#include <string>#include <fstream>using namespace std;int CountSubString(string const& str, string const& substr){ int nCount = 0; string::size_type substrSize = substr.size(); string::size_type idxSub = str.find(substr, 0); //int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置 while (idxSub!=string::npos) { ++nCount; ++idxSub; idxSub = str.find(substr, idxSub); } return nCount;}int CountStrInFile(string const& filename, string const& str){ ifstream inf(filename.c_str()); // c_str():生成一个const char*指针,指向以空字符终止的数组。 //ifstream filename("d:\\test.txt");//以输入方式打开文件 if (!inf) { cout<<"Error: can't open the file: "<<filename<<endl; exit(1); } string infStr; int nSubStrFound = 0; while (inf && !inf.eof()){ inf>>infStr; nSubStrFound += CountSubString(infStr, str); } return nSubStrFound;}int main(){ string filename("d:\\test.txt"); // the file name to search string string strToCount("abc"); // the string to count int nCount = CountStrInFile(filename, strToCount); cout<<nCount<<" times of \""<<strToCount<<"\" found in file: "<<filename<<endl; strToCount = "aaa"; nCount = CountStrInFile(filename, strToCount); cout<<nCount<<" times of \""<<strToCount<<"\" found in file: "<<filename<<endl; system("pause"); return 0;}
//测试文件test.txt内容:
abc abc abc lpte yejylyyryryljryjrabc
logyy[yuuujabcabc
aaaaaa aabeee aaa
//测试输出:
6 times of "abc" found in file: d:\temp\test.txt
5 times of "aaa" found in file: d:\temp\test.txt
0 0
- 指定文件中查找一个字符串并显示该字符串出现的次数
- 查找指定字符串在原始字符串中出现的次数
- 查找一个字符串在另一个字符串中出现的次数
- 在一个字符串中查找另一个字符串出现的次数
- 一个字符串中查找另一个字符串出现的次数
- 在一句话中查找指定字符串出现的次数
- 在TXT文件中查找指定字符串并显示指定字符串所在行的内容
- NSString 查找指定字符串出现的次数
- NSString 查找指定字符串出现的次数
- 查找一个字符串中出现次处最多的那个字符,并输出出现次数
- 查找指定字符串出现次数
- 通过键盘输入一个字符串,判断字符串中出现最多的字符并输出该字符和输出出现次数
- 查找一个字符串中每个单词的出现次数--Java
- 查找字符串中出现li的次数!
- 编写一个方法,输出在一个字符串中,指定字符串出现的次数
- 【Java】编写一个方法,输出在一个字符串中,指定字符串出现的次数
- 查找一个字符串在另一个字符串出现的次数源码
- 统计一个字符串在文件中出现的次数
- ServletContext对象
- 【实战】快速集成自定义转场动画&手势驱动
- IO多路复用之select总结
- 各种IE兼容模式代码,IE6,IE7,IE8,IE9,IE10
- 清除浮动的几种方法
- 指定文件中查找一个字符串并显示该字符串出现的次数
- 我的投资可行吗?
- jsonp跨域调用代码实例
- 2015-12-IOS 获取最新设备型号方法
- 记录一下sqlite中多表查询。
- Java自定义注解和运行时靠反射获取注解
- iOS--坐标变换Quartz 2D中的CGContextTranslateCTM、CGContextScaleCTM、
- Spark on mesos的坑以及解决办法
- Java SE-运算符