1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
|
#include <cstring>
#include <iostream>
#include "string1.h"
#include <ctype.h>
using std::cin;
using std::cout;
// initializing static class member
int String::num_strings = 0;
//static method
int String::HowMany()
{
return num_strings;
}
//class methods
String::String(const char * s)
{
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
num_strings++;
}
String::String()
{
len = 1;
str = new char[1];
str[0] = '\0';
num_strings++;
}
String::String( const String & st)
{
num_strings++;
len = st.len;
str = new char [len + 1];
std::strcpy(str , st.str);
}
String::~String()
{
--num_strings;
delete [] str;
}
//overloaded operator methods
// assign a String to a String
String & String::operator=(const String & st)
{
if( this == &st)
return *this;
delete [] str;
len = st.len;
str = new char[len + 1];
std::strcpy(str, st.str);
return *this;
}
//assign a c string to a string
String & String::operator=(const char * s)
{
delete [] str;
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
return *this;
}
char & String::operator[](int i)
{
return str[i];
}
//read-only char access for const String
const char & String::operator[](int i) const
{
return str[i];
}
//overloaded operator friends
bool operator<(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) < 0);
}
bool operator>(const String &st1, const String &st2)
{
return st2 < st1;
}
bool operator==(const String &st1, const String &st2)
{
return (std::strcmp(st1.str, st2.str) == 0);
}
ostream & operator<<(ostream & os, const String & st)
{
os << st.str;
return os;
}
istream & operator>>(istream & is, String & st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if (is)
st = temp;
while (is && is.get() != '\n')
continue;
return is;
}
String operator+(const String &st, const String &st2)
{
String str;
str.str = new char[st.len + st2.len + 1];
std::strcpy(str.str, st.str);
std::strcpy(st.len + str.str, st2.str);
str.len = std::strlen(str.str);
return str;
}
void String::stringlow()
{
int i = 0;
while(str[i])
{
str[i] = tolower(str[i]);
i++;
}
}
void String::stringup()
{
int i = 0;
while(str[i])
{
str[i] = toupper(str[i]);
i++;
}
}
int String::has(char ch)
{
int count = 0;
int i = 0;
while(str[i])
{
if(str[i] == ch)
count++;
i++;
}
return count;
}
|