当初为了笔试,自己准备了一个,比较简单,所以距离一个比较好的String Builder还是有差距的,仅供参考:)
不排版了阿:P
#include <stdio.h>
#include <string.h>
#include <malloc.h>
class String
{
private:
char* m_str;
int m_nSize;
int m_nLength;
public:
String(){ m_str = NULL; m_nSize = m_nLength = 0; };
String(const char* pChar)
{
if(pChar != NULL)
{
m_nLength = strlen(pChar);
m_nSize = m_nLength+1;
m_str = (char*)malloc(m_nSize*sizeof(char));
strcpy(m_str, pChar);
}
else
{
m_nSize = 0;
m_nLength = 0;
m_str = NULL;
}
};
String(const String& rhs)
{
if(rhs.GetLength() != 0)
{
m_nLength = rhs.GetLength();
m_nSize = m_nLength+1;
m_str = (char*)malloc(m_nSize*sizeof(char));
strcpy(m_str, rhs.m_str);
}
else
{
m_nSize = 0;
m_nLength = 0;
m_str = NULL;
}
};
String& operator=(const String& rhs)
{
if(this == &rhs) return(*this);
else
{
if(rhs.m_str == NULL)
{
free(m_str);
m_str = NULL;
m_nSize = m_nLength = 0;
return(*this);
}
else
{
if(m_str == NULL)
{
m_nSize = rhs.GetLength() + 1;
m_str = (char*)malloc(m_nSize*sizeof(char));
}
else
{
if(m_nSize < rhs.GetLength() + 1)m_nSize = rhs.GetLength() + 1;
m_str = (char*)realloc(m_str,m_nSize*sizeof(char));
}
strcpy(m_str, rhs.m_str);
m_nLength = strlen(m_str);
}
return(*this);
}
};
String& operator+(const String& rhs)
{
if(GetLength() == 0)(*this) = rhs;
else
{
if(rhs.GetLength() == 0)
{
free(m_str);
m_str = NULL;
m_nSize = m_nLength = 0;
}
else
{
if(m_nSize < GetLength() + rhs.GetLength() + 1)m_nSize = GetLength() + rhs.GetLength() + 1;
m_str = (char*)realloc(m_str,m_nSize*sizeof(char));
strcat(m_str, rhs.m_str);
m_nLength = strlen(m_str);
}
}
return(*this);
};
int GetLength() const { return(m_nLength); };
void Display() const { puts(m_str); };
~String(){ if(m_str != NULL)free(m_str); };
};
PS: 关于加号两边可以跟不同的类型读者自己搞定,有的时候要用友元函数,呵呵;不过真的笔试应该没有那么多时间来完善,这样子应该可以了吧。