1

implement operator* for string

This commit is contained in:
2022-08-01 19:36:35 +02:00
parent 3b3bf662ca
commit a7e7e65468
2 changed files with 32 additions and 0 deletions

View File

@ -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 << " ";

View File

@ -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;
}