I wrote a string class. Maybe I can used it in the future.
//GString.h
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
class GString {
private:
char *_buf;
int _len;
public:
GString() : _buf(NULL), _len(0) {}
GString(char *s) : _buf(NULL), _len(0) {
if (s){
_len = strlen(s);
if (_len > 0) {
_buf = new char[_len + 1];
strncpy(_buf, s, _len);
_buf[_len] = 0;
}
else {
_len = 0;
_buf = NULL;
}
}
}
GString(GString& s) : _buf(NULL), _len(0) {
_len = s.getLength();
if (_len > 0) {
delete [] _buf;
_buf = new char[_len + 1];
memset(_buf, 0, (_len + 1));
strncpy(_buf, s.to_cstr(), _len);
}
else {
_len = 0;
_buf = NULL;
}
}
~GString() {
if (_buf) {
delete [] _buf;
_len = 0;
}
}
GString& operator= (const GString& s) {
if (this == &s)
return *this;
_len = s.getLength();
delete [] _buf;
_buf = new char[_len + 1];
memset(_buf, 0, (_len + 1));
strncpy(_buf, s.to_cstr(), _len);
return *this;
}
char operator[] (const int index) const {
char r = '/0';
if ((index >= 0) && (index <= _len))
r = _buf[index];
return r;
}
inline int getLength() const {
return _len;
}
const char *to_cstr() const {
return _buf;
}
GString& operator+(const GString& s) {
char *p = new char[_len + s.getLength() + 1];
if (p) {
strncpy(p, _buf, _len);
strncpy(&p[_len], s.to_cstr(), s.getLength());
_len += s.getLength();
p[_len] = '/0';
delete [] _buf;
_buf = p;
}
return *this;
}
bool operator==(const GString& s) const {
const char *p = s.to_cstr();
if (&s == this) return true;
return (strcmp(_buf, p) == 0) ? true : false;
}
bool operator!=(const GString& s) const {
const char *p = s.to_cstr();
if (&s != this) return true;
return (strcmp(_buf, p) != 0) ? true : false;
}
GString substring(int offset, int len) {
char buf[1024];
memset(buf, 0, sizeof(buf));
if ((offset >= 0) && (offset <= _len)) {
len = (len <= 0) ? 1 : len;
len = min(len, _len - offset);
strncpy(buf, &_buf[offset], len);
GString r(buf);
cout<<"> "<<r.to_cstr()<<endl;
return r;
}
GString s;
return s;
}
};
int main() {
GString s("abc");
for (int i = 0; i <= s.getLength(); i++)
cout<<s[i];
cout<<endl;
GString cs(s);
cout<<cs.to_cstr()<<endl;
GString ms("luming ");
cout<<ms.to_cstr()<<endl;
ms + s;
cout<<ms.to_cstr()<<endl;
ms = s;
cout<<ms.to_cstr()<<endl;
if (ms==s)
cout<<"true"<<endl;
else cout<<"false"<<endl;
if (ms!=s)
cout<<"true"<<endl;
else cout<<"false"<<endl;
GString sub;
sub = ms.substring(0, 1);
cout<<sub.to_cstr()<<endl;
return 0;
}
June 15th Monday (六月 十五日 月曜日)
最新推荐文章于 2021-06-21 09:50:10 发布