implement operator* for string
This commit is contained in:
@ -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 << " ";
|
||||
|
@ -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;
|
||||
}
|
||||
|
Reference in New Issue
Block a user