C/C++ code#include
#include
using namespace std;
class SString
{
friend ostream &operator<
public:
SString(const char *s = NULL); // 构造
SString(const SString &s); // 拷贝构造
~SString() { }
SString &operator=(const SString &s); // 重载赋值
char *GetStr() { return str; }
// 由s1和s2联接而成的新串。若未截断,则返回true,否则false
bool Concat(const SString &s1, const SString &s2);
// 用sub返回第pos个字符起长度为len的子串。
bool SubString(SString &sub, int pos, int len) const;
// 在第pos个字符之前插入串t
bool StrInsert(int pos, const SString &t);
protected:
char str[256];
};
ostream &operator<
{
output << s.str;
return output;
}
SString::SString(const char *s) // 构造
{
int i;
this->str[0] = '\0';
if (s != NULL)
{
for (i = 0; s[i] != '\0' && i < 255; ++i)
this->str[i] = s[i];
this->str[i] = '\0';
}
}
SString::SString(const SString &s) // 拷贝构造
{
int i;
for (i = 0; s.str[i] != '\0'; ++i)
this->str[i] = s.str[i];
this->str[i] = '\0';
}
SString &SString::operator=(const SString &s) // 重载赋值
{
int i;
for (i = 0; s.str[i] != '\0'; ++i)
this->str[i] = s.str[i];
this->str[i] = '\0';
return *this;
}
// 由s1和s2联接而成的新串。若未截断,则返回true,否则false
bool SString::Concat(const SString &s1, const SString &s2)
{
int len1 = strlen(s1.str), len2 = strlen(s2.str);
int i;
if (len1 + len2 < 255) // 未截断
{
for (i = 0; i < len1; ++i)
this->str[i] = s1.str[i];
for (i = 0; i < len2; ++i)
this->str[i + len1] = s2.str[i];
this->str[i + len1] = '\0';
return true;
}
else if (len1 < 255) // 截断
{
for (i = 0; i < len1; ++i)
this->str[i] = s1.str[i];
for (i = len1 + 1; i < 256; ++i)
this->str[i] = s2.str[i - len1];
this->str[i] = '\0';
return false;
}
else // 截断(仅取s1)
{
for (i = 0; i < 255; ++i)
this->str[i] = s1.str[i];
this->str[i] = '\0';
return false;
}
}
// 用sub返回第pos个字符起长度为len的子串。
bool SString::SubString(SString &sub, int pos, int len) const
{
int thislen = strlen(this->str);
int i;
if (pos < 0 || pos > thislen || len < 0 || len > thislen - pos + 1)
return false;
for (i = 0; i < len; ++i)
sub.str[i] = this->str[pos + i - 1];
sub.str[i] = '\0';
return true;
}
// 在第pos个字符之前插入串t
bool SString::StrInsert(int pos, const SString &t)
{
int i;
int thislen = strlen(this->str);
int len = strlen(t.str);
if (pos < 0 || pos > thislen)
return false;
if (thislen + len >= 255)
return false;
for (i = thislen - 1; i >= pos; --i)
this->str[i + len] = this->str[i];
for (i = 0; i < len; ++i)
this->str[pos + i] = t.str[i];
this->str[thislen + len] = '\0';
return true;
}
int main()
{
SString a("abcdefgh");
SString b = "12345678";
SString c, s;
cout << a << endl;
cout << b << endl;
c.Concat(a, b);
cout << c << endl;
c.SubString(s, 8, 6);
cout << s << endl;
s.StrInsert(3, "ABCDEEGH");
cout << s << endl;
return 0;
}