Code:
#include <iostream>
#include <string>
class StrRef {
bool dynamic;
std::string *base;
int index;
int overwrite;
public:
StrRef(const char *init, int at, int rep);
StrRef(std::string& init, int at, int rep);
~StrRef();
std::string operator=(std::string s);
std::string operator=(StrRef ref);
operator std::string();
};
StrRef::StrRef(const char *init, int at, int rep):
dynamic(true), base(new std::string(init)),
index(at), overwrite(rep)
{}
StrRef::StrRef(std::string& init, int at, int rep):
dynamic(false), base(&init),
index(at), overwrite(rep)
{}
StrRef::~StrRef()
{
if (dynamic)
delete base;
}
std::string StrRef::operator=(std::string s)
{
base->replace(index, overwrite, "");
base->insert(index, s);
return *base;
}
std::string StrRef::operator=(StrRef ref)
{
base->replace(index, overwrite, "");
base->insert(index, *ref.base, ref.index, ref.base->length());
return *base;
}
StrRef::operator std::string()
{
return base->substr(index, overwrite);
}
StrRef Mid(const char *s, int at, int rep = 0)
{
return StrRef(s, at, rep);
}
StrRef Mid(std::string& s, int at, int rep = 0)
{
return StrRef(s, at, rep);
}
// Contest test program
int main()
{
using namespace std;
bool correct = true;
string s1,s2;
//Basic test
s2 = "0123456789";
string s3 = Mid(s2,1,4);
s1 = Mid(s2,1,4);
s2 = Mid("0123456789",1,4);
if (s1 != "1234" || s2 != "1234" || s3 != "1234")
cout << "Basic test incorrect : " << s1, correct=false;
//First test
s1 = "abcdefg";
Mid(s1, 3, 0) = "123";
if (s1 != "abc123defg")
cout << "First test incorrect : " << s1, correct=false;
//Second test
s1 = "abcdefg";
s2 = "123";
Mid(s1, 3, s2.size()) = s2;
if (s1 != "abc123g")
cout << "Second test incorrect : " << s1, correct=false;
//Third test
s1 = "abc";
s2 = "123";
Mid(s1, 1, 1) = Mid(s2,1);
if (s1 != "a23c")
cout << "Third test incorrect : " << s1, correct=false;
if (correct)
cout << "All tests correct!";
cin.get();
}
Tested on the following compilers: