From 1060f8508969b52c45841ae1bf73663e6bf32f4b Mon Sep 17 00:00:00 2001 From: Relintai Date: Sun, 6 Feb 2022 13:43:56 +0100 Subject: [PATCH] Added find_reversed and file_get_extension helpers to string. --- core/string.cpp | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ core/string.h | 3 +++ 2 files changed, 69 insertions(+) diff --git a/core/string.cpp b/core/string.cpp index 3f13bc8..4bf7b46 100644 --- a/core/string.cpp +++ b/core/string.cpp @@ -153,6 +153,62 @@ int String::find(const String &val, const int from) const { return -1; } +int String::find_reversed(const char val, const int from) const { + if (_size == 0) { + return -1; + } + + int f; + + if (from < 0) { + f = _size - 1; + } else { + f = from - 1; + } + + for (int i = f; i >= 0; --i) { + if (_data[i] == val) { + return i; + } + } + + return -1; +} + +int String::find_reversed(const String &val, const int from) const { + if (_size == 0) { + return -1; + } + + if (_size < val.size()) { + return -1; + } + + int ve; + + if (from < 0) { + ve = _size - val.size() - 1; + } else { + ve = from - 1; + } + + for (int i = ve; i >= 0; --i) { + bool found = true; + for (int j = 0; j < val.size(); ++j) { + if (_data[i + j] != val[j]) { + found = false; + break; + } + } + + if (found) { + return i; + } + } + + return -1; +} + void String::get_substr(char *into_buf, const int start_index, const int len) { ERR_FAIL_INDEX(start_index + len - 1, _size); @@ -1150,6 +1206,16 @@ String String::path_get_prev_dir() const { return substr_index(0, seind); } +String String::file_get_extension() const { + int dind = find_reversed('.'); + + if (dind == -1) { + return Stirng(); + } + + return substr_index(dind + 1, _size - 1); +} + void String::to_html_special_chars() { replace("&", "&"); replace("\"", """); diff --git a/core/string.h b/core/string.h index 5eb57ba..12aede8 100644 --- a/core/string.h +++ b/core/string.h @@ -33,6 +33,8 @@ public: void resize(const int s); int find(const char val, const int from = 0) const; int find(const String &val, const int from = 0) const; + int find_reversed(const char val, const int from = -1) const; + int find_reversed(const String &val, const int from = -1) const; void get_substr(char *into_buf, const int start_index, const int len); void get_substr_nt(char *into_buf, const int start_index, const int len); String substr(const int start_index, const int len) const; @@ -114,6 +116,7 @@ public: String path_get_basename() const; String path_get_last_segment() const; String path_get_prev_dir() const; + String file_get_extension() const; void to_html_special_chars(); void from_html_special_chars();