FindLetter 类——查找文件中特定的字符,每一行开头为某一个字符,则跳过

时间:2021-10-01 14:42:14
 1 /*统计除了>之外的行里面CHED四个字母总数*/
 2 #include<fstream>
 3 #include<iostream>
 4 #include<cstring>
 5 using namespace std;
 6 
 7 class FindLetter
 8 {
 9     private:
10         ifstream m_r;
11         ofstream m_w;
12         string m_falphabet,m_temp;
13         char m_jump;//要跳跃的字符
14         unsigned int *m_number,m_length;//计数 和 文件中的一行的个数
15     public:
16         FindLetter(const char * falphabet,char jump)
17         //参数意思为:第一个参数,要找的字符串;第二个参数,在此行的第一个字符是jump不读取。
18         {
19             m_jump=jump;
20             m_falphabet=falphabet;
21             m_number=new unsigned int [m_falphabet.length()];
22             memset(m_number,0,sizeof(int)*m_falphabet.length());
23 
24 
25         }
26         ~FindLetter()
27         {
28             delete []m_number;
29             m_r.close();
30             m_w.close();
31         }
32         void setFindLetter(const char *falphabet,const char jump)//与构造函数相同
33         {
34             //写完后,请尝试this指针 调用构造函数
35                 m_jump=jump;
36                 m_falphabet=falphabet;
37                 m_number=new unsigned int[m_falphabet.length()];
38                 memset(m_number,0,sizeof(int)*m_falphabet.length());
39 
40         }
41         void countAlphabet(const char * filename);
42         bool wTxt(const char * filename);
43 };
44 void FindLetter::countAlphabet(const char * filename)
45 {
46     m_r.open(filename);
47     while(getline(m_r,m_temp))
48         {
49             m_length=m_temp.length();//文本文件中的一行字符的长度。
50 
51                 while(--m_length!=-1&&m_temp[0]!=m_jump)
52                 {
53                     int temp=m_falphabet.length();
54                     //判断是否为要找的字符
55                     while(--temp!=-1)//从n-0数
56                         if(m_falphabet[temp]==m_temp[m_length])
57                         {
58                             ++m_number[temp];
59 
60                         }
61                 }
62 
63         }
64     for(int i=m_falphabet.length()-1;i>=0;--i)
65         cout<<m_falphabet[i]<<" : "<<m_number[i]<<endl;
66 }
67 bool FindLetter::wTxt(const char * filename)
68 {
69     m_w.open(filename);
70 
71     for(int i=m_falphabet.length()-1;i>=0;--i)
72         m_w<<m_falphabet[i]<<" : "<<m_number[i]<<endl;
73 }

此用以备忘!!!