so im working on a little project to help me learn more about stings and about linked lists. this is my first time using c++ as i usually use c
i have my header file MyString.h
#pragma once
#include <iostream>
#include <string.h>
#include <cstring>
class String
{
private:
char* str;
public:
String();
String(const char* s);
~String();
char* GetString();
////////
int GetLength()
{
return std::strlen(str);
}
String& operator = (const char* s);
char& operator[] (int index);
String& operator +(String& s);
};
and my MyString.cpp
#include <iostream>
#include <string.h>
#include "MyString.h"
#include <cassert>
String::String()
{
str = nullptr;
}
String::String(const char* s)
{
int len = strlen(s);
str = new char[len+1];
strcpy(str, s);
}
String::~String()
{
std::cout << "clean string: ";
if (str == nullptr)
std::cout << "nullptr";
else
std::cout << str;
std::cout << "n";
if (str != nullptr)
delete [] str;
}
char* String::GetString()
{
return str;
}
String& String::operator=(const char* s)
{
// TODO: insert return statement here
if (str != nullptr)
{
delete[] str;
}
int len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
return *this;
}
char& String::operator[](int index)
{
assert(index >= 0 && index < GetLength());
return str[index];
}
im trying to make it work where if i try this
String s1 = "Hello";
String s2 = "There";
s3 = s1 + s2;
Print(s3.GetString());
it would print as “Hello There”
but im lost on how to write a function where even if i add more strings it automatically formats it and prints it.
i can do this for example
std::string s3 = s1 + " " + s2;
but i dont want to do it for each individual print statement.
user26695080 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1