diff --git a/c_os/user/demo/StringDemo.cc b/c_os/user/demo/StringDemo.cc index 5b9889c..334f791 100644 --- a/c_os/user/demo/StringDemo.cc +++ b/c_os/user/demo/StringDemo.cc @@ -26,6 +26,10 @@ void StringDemo::run() { str3 += " World"; kout << str3 << endl; + kout << "Hello World *= 3" << endl; + str3 *= 3; + kout << str3 << endl; + kout << "String iterator!" << endl; for (const char c : str1) { kout << c << " "; diff --git a/c_os/user/lib/String.h b/c_os/user/lib/String.h index 9cc2b08..bf79d07 100644 --- a/c_os/user/lib/String.h +++ b/c_os/user/lib/String.h @@ -4,6 +4,8 @@ #include "user/lib/Array.h" #include "user/lib/Iterator.h" +// A heap dynamically heap-allocated string (mutable) + namespace bse { unsigned int strlen(const char* str); @@ -132,6 +134,32 @@ namespace bse { return *this; } + string operator*(unsigned int n) const { + string new_str; + new_str.len = len * n; + new_str.buf = new char[new_str.len]; + + for (unsigned int i = 0; i < n; ++i) { + strncpy(&new_str.buf[i * len], len, buf); + } + + return new_str; + } + + string& operator*=(unsigned int n) { + unsigned int new_len = len * n; + char* new_buf = new char[new_len]; + + for (unsigned int i = 0; i < n; ++i) { + strncpy(&new_buf[i * len], len, buf); + } + + delete[] buf; + buf = new_buf; + len = new_len; + return *this; + } + bool operator==(const string& other) const { return strcmp(buf, other.buf) == 0; }