#include <iostream>
#include <string.h>
using namespace std;
class CString
{
public:
CString(char *s, char s1[], char *s2);
void Replace();
void Show();
~CString();
private:
char *str;
char *str1;
char *str2;
int flag;
};
CString::CString(char *s, char s1[], char *s2)
{
str = new char[strlen(s) + 1];
str1 = new char[strlen(s1) + 1];
str2 = new char[strlen(s2) + 1];
strcpy(str, s);
strcpy(str1, s1);
strcpy(str2, s2);
flag = 0;
}
void CString::Replace()
{
char *temp1 = str1;
char *temp_str = str;
while (*temp_str!='\0')
{
while(*temp_str == *temp1)
{
temp_str++;
temp1++;
if(*temp1 == '\0')
{
flag = 1;
char *r_str = new char[strlen(temp_str) + 1];
strcpy(r_str, temp_str); //取出要目标字符串后面的字符串
char *l_str = temp_str-strlen(str1); //指向目标字符串
strcpy(l_str, str2); //复制替换目标字符串
strcat(l_str, r_str); //拼接两段字符串
temp_str = temp_str-strlen(str1)+strlen(str2)-1; //temp_str指向替换了的字符串末尾
delete[] r_str;
}
}
if(strlen(temp_str)<strlen(str1))
break;
temp_str++;
temp1 = str1;
}
}
void CString::Show()
{
if(flag == 1)
{
cout << "目标关键字:" << str1 <<endl;
cout << "替换关键字:" << str2 << endl;
cout << "替换字符串:" << str << endl;
}
else
{
cout << "原始字符串:" << str << endl;
}
}
CString::~CString()
{
if (str != NULL) {
delete[] str;
str = NULL;
}
if (str1 != NULL) {
delete[] str1;
str1 = NULL;
}
if (str2 != NULL) {
delete[] str2;
str2 = NULL;
}
}
int main(int argc, const char * argv[]) {
char s[] = "I am a student, you are student too, we are all student.";
char s1[] = "student";
char s2[] = "teacher";
CString test(s, s1, s2);
test.Replace();
test.Show();
return 0;
}
|