Added more helpers to string, and fixed a bug in replace_from.

This commit is contained in:
Relintai 2021-11-20 21:39:30 +01:00
parent ff8790f81d
commit f9dcd088d0
2 changed files with 134 additions and 49 deletions

View File

@ -233,12 +233,12 @@ void String::replace_from(const int start_index, const int length, const String
}
_size -= loffs;
}
} else {
for (int i = 0; i < length; ++i) {
_data[i + start_index] = with._data[i];
}
}
}
void String::replace(const String &find_str, const String &with) {
if (empty()) {
@ -255,6 +255,29 @@ void String::replace(const String &find_str, const String &with) {
}
}
void String::replace(const String &find_str, const String &with, const int count) {
if (empty()) {
return;
}
if (find_str.empty())
return;
int c = 0;
int start_pos = 0;
while ((start_pos = find(find_str, start_pos)) != -1) {
replace_from(start_pos, find_str.size(), with);
start_pos += with.size();
++c;
if (c == count) {
return;
}
}
}
int String::compare(const String &other) const {
if (size() < other.size()) {
return 1;
@ -357,6 +380,61 @@ void String::trim_end() {
_size = last_index;
}
bool String::ends_with(const char c) const {
if (_size == 0) {
return false;
}
return _data[_size - 1] == c;
}
bool String::ends_with(const String &str) const {
if (str.size() == 0) {
// maybe this should be false?
return true;
}
if (_size < str.size()) {
return false;
}
int diff = _size - str.size();
for (int i = str.size() - 1; i >= 0; --i) {
if (_data[i + diff] != str._data[i]) {
return false;
}
}
return true;
}
bool String::starts_with(const char c) const {
if (_size == 0) {
return false;
}
return _data[0] == c;
}
bool String::starts_with(const String &str) const {
if (str.size() == 0) {
// maybe this should be false?
return true;
}
if (_size < str.size()) {
return false;
}
for (int i = 0; i < str.size(); ++i) {
if (_data[i] != str._data[i]) {
return false;
}
}
return true;
}
int String::get_slice_count(const char splitter) const {
int count = 1;

View File

@ -35,6 +35,7 @@ public:
void replace_from(const int start_index, const int length, const String &with);
void replace(const String &find_str, const String &with);
void replace(const String &find_str, const String &with, const int count);
int compare(const String &other) const;
@ -45,6 +46,12 @@ public:
void trim_beginning();
void trim_end();
bool ends_with(const char c) const;
bool ends_with(const String &str) const;
bool starts_with(const char c) const;
bool starts_with(const String &str) const;
int get_slice_count(const char splitter) const;
int get_slice_count(const String &splitter) const;
String get_slice(const char splitter, int index);