改写要求1:将字符数组str改为字符指针p,动态开辟存储空间
改写要求2:增加统计关键字个数的函数void CountKeyWords()
改写要求3: 增加替换函数void FindKeyWords()
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std; class WORDNUM
{
char *p;
double c;
public:
WORDNUM(char *s)
{
p=new char[strlen(s)];
strcpy(p,s);
c=;
}
void process();
void CountKeyWords(string key[],int len);
void FindKeyWords(string key[],string swapkey[],int len);
void print()
{
char* r=new char[strlen(p)];
strcpy(r,p);
while(*r!='\0')
cout<<*(r++);
cout<<endl;
cout<<"num="<<c<<endl;
}
}; void WORDNUM::CountKeyWords(string key[],int len)
{
int i=len;
while(i)
{
double sameword=;
char* r=new char[strlen(p)];
strcpy(r,p);
char* q=new char[key[i-].length()];
strcpy(q,key[i-].c_str());
char* find=strstr(r,q);
while(find)
{
memset(find, ' ', strlen(q));
sameword++;
find=strstr(find,q); } cout<<key[i-]<<"的个数为:"<<sameword<<"占全部字符"<<(sameword/c)*<<"%"<<endl;
i--;
}
} void WORDNUM::FindKeyWords(string key[],string swapkey[],int len)
{
int i=len;
string temp;
temp=p;
int pos=temp.find(key[i-]);
while(i)
{
while(pos!=-)
{
temp.replace(pos,key[i-].length(),swapkey[i-]);
pos=temp.find(key[i-]); }
i--;
}
memset(p,,sizeof(p));
strcpy(p,temp.c_str());
} void WORDNUM::process()
{
int word=;
int len;
len=strlen(p);
char* r=new char[strlen(p)];
strcpy(r,p);
for(int i=;i<len;i++)
{
if(((r[i]>='a'&&r[i]<='z')||(r[i]>='A'&&r[i]<='Z'))&&word)
{
c++;
word=;
}
else if(r[i]==' ')
word=;
}
} int main(int argc, char *argv[])
{
string key[]={"nice","girl"};
string swapkey[]={"ugly","boy"};
int len=sizeof(key)/sizeof(key[]);
string str="She is a nice nice girl girl girl hi";
char* split=new char[strlen(str.c_str())];
strcpy(split,str.c_str());
WORDNUM w(split);
w.process();
w.CountKeyWords(key,len);
w.print();
w.FindKeyWords(key,swapkey,len);
w.print();
system("PAUSE");
return EXIT_SUCCESS;
}