插入:
去掉字符串两端的空白:
DTString.h更新如下:
1 #ifndef DTSTRING_H 2 #define DTSTRING_H 3 4 #include "Object.h" 5 6 namespace DTLib 7 { 8 9 class String : Object 10 { 11 protected: 12 char* m_str; 13 int m_length; 14 15 void init(const char* s); 16 bool equal(const char* l, const char* r, int len) const; 17 public: 18 String(); 19 String(char c); 20 String(const char* s); 21 String(const String& s); 22 23 int length() const; 24 const char* str() const; 25 26 bool startWith(const char* s) const; 27 bool startWith(const String& s) const; 28 bool endOf(const char* s) const; 29 bool endOf(const String& s) const; 30 31 String& insert(int i, const char* s); 32 String& insert(int i, const String& s); 33 34 String& trim(); 35 36 char& operator [] (int i); 37 char operator [] (int i) const; 38 39 bool operator == (const String& s) const; 40 bool operator == (const char* s) const; 41 42 bool operator != (const String& s) const; 43 bool operator != (const char* s) const; 44 45 bool operator > (const String& s) const; 46 bool operator > (const char* s) const; 47 48 bool operator < (const String& s) const; 49 bool operator < (const char* s) const; 50 51 bool operator >= (const String& s) const; 52 bool operator >= (const char* s) const; 53 54 bool operator <= (const String& s) const; 55 bool operator <= (const char* s) const; 56 57 String operator + (const String& s) const; 58 String operator + (const char* s) const; 59 String operator += (const String& s); 60 String operator += (const char* s); 61 62 String& operator = (const String& s); 63 String& operator = (const char* s); 64 String& operator = (char c); 65 66 ~String(); 67 }; 68 69 } 70 71 72 #endif // DTSTRING_H
DTString.cpp更新如下:
1 #include <cstring> 2 #include <cstdlib> 3 #include "DTString.h" 4 #include "Exception.h" 5 6 using namespace std; 7 8 namespace DTLib 9 { 10 11 void String::init(const char* s) 12 { 13 m_str = strdup(s); 14 15 if( m_str ) 16 { 17 m_length = strlen(m_str); 18 } 19 else 20 { 21 THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create string object ..."); 22 } 23 } 24 25 bool String::equal(const char* l, const char* r, int len) const 26 { 27 bool ret = true; 28 29 for(int i = 0; i < len && ret; i++) 30 { 31 ret = ret && (l[i] == r[i]); 32 } 33 34 return ret; 35 } 36 37 String::String() 38 { 39 init(""); 40 } 41 42 String::String(const char* s) 43 { 44 init(s ? s : ""); //空指针就转换成空字符串 45 } 46 47 String::String(const String& s) 48 { 49 init(s.m_str); 50 } 51 52 String::String(char c) 53 { 54 char s[] = {c, '