Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <iostream>
- #include <cstring>
- using namespace std;
- class String {
- public:
- String() : size(0), capacity(15), str(new char[15]) {}
- String(const int string_capacity) : size(0), capacity(string_capacity), str(new char[string_capacity]) {}
- String(const char new_str[]) {
- capacity = strlen(new_str) + 1;
- str = new char[capacity];
- strcpy(str, new_str);
- size = capacity - 1;
- }
- void SetString(const char new_str[]) {
- int new_space = strlen(new_str) + 1;
- if (capacity < new_space) {
- delete[] str;
- capacity = new_space;
- str = new char[capacity];
- }
- strcpy(str, new_str);
- size = capacity - 1;
- }
- const char* GetString() {
- return str;
- }
- void SetChar(const int index, const char ch) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- return;
- }
- str[index] = ch;
- }
- char GetChar(const int index) {
- if (index < 0 || index >= size) {
- cout << "Invalid index" << endl;
- abort;
- }
- return str[index];
- }
- int Size() {
- return size;
- }
- int Capacity() {
- return capacity;
- }
- ~String() {
- delete[] str;
- }
- private:
- int size;
- int capacity;
- char* str;
- };
- int main() {
- String my_string;
- cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
- my_string.SetString("Hello");
- cout << my_string.GetString() << endl;
- cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
- my_string.SetString("Hello my dear friend");
- cout << my_string.GetString() << endl;
- cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
- my_string.SetChar(2, 'm');
- cout << my_string.GetString() << endl;
- cout << my_string.GetChar(1) << endl;
- String my_new_string("1234");
- cout << my_new_string.GetString() << endl;
- cout << "Size: " << my_new_string.Size() << " Capacity: " << my_new_string.Capacity() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement