// Exercise1.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
//
#include <iostream>
class String
{
public:
String (const char * string)
{
m_length = strlen(string);
m_value = new char[m_length + 1];
memcpy(m_value, string, m_length + 1);
}
~String()
{
delete[] m_value;
}
size_t GetLength() const
{
return m_length;
}
const char* c_str() const
{
return m_value;
}
void Concatenate(const String& str)
{
Concatenate(str.c_str());
}
///Used this solution: https://puu.sh/BVyEB/f697b8b781.png
void Concatenate(const char* str)
{
const auto n_length = strlen(str);
const auto n_string = new char[m_length + n_length + 1]; //Add the old length and the new length + 1 for \0
memcpy(n_string, m_value, m_length);
memcpy(n_string + m_length, str, n_length + 1);
delete[] m_value; //Delete the old HeapMem to save the new pointer in the next line
m_value = n_string;
m_length += n_length;
}
private:
char* m_value;
size_t m_length;
};
int main()
{
const auto str = "MyVision";
const String yourString(str);
String myString("Hello");
myString.Concatenate("World");
const auto m_length = myString.GetLength();
const auto y_length = yourString.GetLength();
std::cout << m_length << std::endl;
std::cout << y_length << std::endl;
myString.Concatenate(yourString);
const auto b_length = myString.GetLength();
std::cout << b_length << std::endl;
const char* cStr = myString.c_str();
std::cout << cStr;
}
Comments