C++程序设计实践指导1.9统计与替换字符串中的关键字改写要求实现
改写要求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=0; } 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=0; char* r=new char[strlen(p)]; strcpy(r,p); char* q=new char[key[i-1].length()]; strcpy(q,key[i-1].c_str()); char* find=strstr(r,q); while(find) { memset(find, ‘ ‘, strlen(q)); sameword++; find=strstr(find,q); } cout<<key[i-1]<<"的个数为:"<<sameword<<"占全部字符"<<(sameword/c)*100<<"%"<<endl; i--; } } void WORDNUM::FindKeyWords(string key[],string swapkey[],int len) { int i=len; string temp; temp=p; int pos=temp.find(key[i-1]); while(i) { while(pos!=-1) { temp.replace(pos,key[i-1].length(),swapkey[i-1]); pos=temp.find(key[i-1]); } i--; } memset(p,0,sizeof(p)); strcpy(p,temp.c_str()); } void WORDNUM::process() { int word=1; int len; len=strlen(p); char* r=new char[strlen(p)]; strcpy(r,p); for(int i=0;i<len;i++) { if(((r[i]>=‘a‘&&r[i]<=‘z‘)||(r[i]>=‘A‘&&r[i]<=‘Z‘))&&word) { c++; word=0; } else if(r[i]==‘ ‘) word=1; } } int main(int argc, char *argv[]) { string key[2]={"nice","girl"}; string swapkey[2]={"ugly","boy"}; int len=sizeof(key)/sizeof(key[0]); 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; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。