//2022_04_02.cpp
// 2022_04_02.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"MyString.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
MyString m1("college",7);
MyString m2("Student",7);
m1.input();
m2.input();
m1.concat(m2);
m1.GetChar(6);
m1.ReplaceChar(1,' ');
char *a="I LOVE China";
MyString msg1(a,strlen(a));
msg1.input();
msg1.Getlength();
char *b="I am tjufe student";
MyString msg2;
msg2.Assign_value(b);
msg2.input();
msg2.Getlength();
system("pause");
return 0;
}
//MyString.h
#pragma once
class MyString
{
char *value;
int size;
public:
MyString();
MyString(char *str,int size);
MyString(const MyString &msg);
void concat(const MyString msg2 );
void Getlength();
void ReplaceChar(int pos,char c);
void GetChar(int pos);
~MyString();
void Assign_value(char *assign);
void input();
};
//MyString.cpp
#include "StdAfx.h"
#include "MyString.h"
#include<iostream>
using namespace std;
//constructor
MyString::MyString()
{
}
MyString::MyString(char *str,int size)
{
this->size=size;
value =new char[size+1];
int i;
for(i=0;i<size;i++)
{
*(value+i)=*str;
str++;
}
this->value[i]='\0';
}
//copy constructor
MyString::MyString(const MyString &msg)
{
this->size=msg.size;
value=new char [size+1];
int i;
for(i=0;i<size;i++)
{
*(this->value+i)=*(msg.value+i);
}
this->value[i]='\0';
}
//concat
void MyString::concat(const MyString msg2)
{
int large =msg2.size+this->size;
char * msg=new char [large+1];
int i,j;
for(i=0;i<this->size;i++)
{
msg[i]=this->value[i];
}
for(i=this->size,j=0;i<large;i++,j++)
{
msg[i]=msg2.value[j];
}
msg[i]='\0';
delete[]value;
value=new char [large+1];
for(i=0;i<large;i++)
{
this->value[i]=msg[i];
}
size=large;
cout<<"m1 concat m2:"<<endl;
this->input();
delete[]msg;
}
//assign value
void MyString:: Assign_value(char *assign)
{int size=strlen(assign);
this->size=size;
value =new char[size+1];
int i;
for(i=0;i<size;i++)
{
*(value+i)=*assign;
assign++;
}
this->value[i]='\0';
}
//getchar
void MyString::GetChar(int pos)
{
if(pos<0||pos>=size)
{
cout<<"the wrong pos";
}
else cout<<"the "<<pos<<" char is "<<value[pos]<<endl;
}
//replace char
void MyString::ReplaceChar(int pos,char c)
{
if(pos<0||pos>=size)
{cout<<"the wrong pos";
}
else
{
this->value[pos]=c;
cout<<"the "<<pos<<"char correct char"<<c<<" :";
for(int i=0;i<size;i++)
{
cout<<value[i];
}
cout<<endl;
}
}
//getlength
void MyString::Getlength()
{
cout<<"the effective string length is"<<size<<endl;
}
//destructor
MyString::~MyString()
{
delete[] value;
}
//input
void MyString::input()
{
for(int i=0;i<size;i++)
{
cout<<value[i];
}
cout<<endl;
}
在学C++的类过程中老师要求用分文件进行写
运行结果: