1. #include <cstring>
  2. #include "string.h"
  3.  
  4. namespace ctm {
  5. int string::num_strings = 0; //initialize static class member
  6.  
  7. int string::HowMany() { //static method
  8. return num_strings;
  9. }
  10.  
  11. //class methods
  12. string::string(const char *s) { //construt string from c-string
  13. len = std::strlen(s); //set size
  14. str = new char [len + 1]; //allocate proper memory size
  15. std::strcpy(str, s); //initialize pointer
  16.  
  17. num_strings++;
  18. }
  19.  
  20. string::string() {
  21. len = 4;
  22. str = new char [4];
  23. str[0] = '\0';
  24.  
  25. num_strings++;
  26. }
  27.  
  28. string::string(const string &st) {
  29. num_strings++;
  30. len = st.len; //same length
  31. str = new char [len + 1];
  32. std::strcpy(str, st.str); //copy string to new location
  33. }
  34.  
  35. string::~string() {
  36. --num_strings;
  37. delete [] str;
  38. }
  39.  
  40. //overloaded operators
  41.  
  42. //assign a string to a string
  43. string &string::operator=(const string &st) { //assignment
  44. if (this == &st)
  45. return *this;
  46.  
  47. delete [] str;
  48. len = st.len;
  49. str = new char [len + 1];
  50. std::strcpy(str, st.str);
  51.  
  52. return *this;
  53. }
  54.  
  55. //assign a c-string to a string
  56. string &string::operator=(const char *s) {
  57. delete [] str;
  58. len = std::strlen(s);
  59. str = new char [len + 1];
  60. std::strcpy(str, s);
  61.  
  62. return *this;
  63. }
  64.  
  65. //read-write char access for NON-CONST string
  66. char &string::operator[](int i) {
  67. return str[i];
  68. }
  69.  
  70. //read-only acess access for cons string
  71. const char &string::operator[](int i) const {
  72. return str[i];
  73. }
  74.  
  75. //overloaded friends
  76. bool operator<(const string &st, const string &st2) {
  77. return (std::strcmp(st.str, st2.str) < 0);
  78. }
  79.  
  80. bool operator>(const string &st, const string &st2) {
  81. return (st2.str < st.str);
  82. }
  83.  
  84.  
  85. bool operator==(const string &st, const string &st2) {
  86. return (std::strcmp(st.str, st2.str) == 0);
  87. }
  88.  
  89.  
  90. //output and input
  91.  
  92. std::ostream &operator<<(std::ostream &os, const string &st) {
  93. os << st.str;
  94.  
  95. return os;
  96. }
  97.  
  98. /*std::istream &operator>>(std::istream &is, const string &st) {
  99. char temp[string::CINLIM];
  100. is.get(temp, string::CINLIM);
  101. if (is) {
  102. st = temp;
  103. }
  104.  
  105. while (is && is.get() != '\n') {
  106. continue;
  107. }
  108.  
  109. return is;
  110. }*/
  111.  
  112. }
  113.