diff --git a/include/SFML/System/String.hpp b/include/SFML/System/String.hpp index 8a0bcf8d0..a8aff0c5c 100644 --- a/include/SFML/System/String.hpp +++ b/include/SFML/System/String.hpp @@ -411,6 +411,32 @@ public : //////////////////////////////////////////////////////////// std::size_t find(const String& str, std::size_t start = 0) const; + //////////////////////////////////////////////////////////// + /// \brief Replace a substring with another string + /// + /// This function replaces the substring that starts at index \a position + /// and spans \a length characters with the string \a replaceWith. + /// + /// \param position Index of the first character to be replaced + /// \param length Number of characters to replace. You can pass InvalidPos to + /// replace all characters until the end of the string. + /// \param replaceWith String that replaces the given substring. + /// + //////////////////////////////////////////////////////////// + void replace(std::size_t position, std::size_t length, const String& replaceWith); + + //////////////////////////////////////////////////////////// + /// \brief Replace all occurrences of a substring with a replacement string + /// + /// This function replaces all occurences of \a searchFor in this string + /// with the string \a replaceWith. + /// + /// \param searchFor The value being searched for + /// \param replaceWith The value that replaces found \a searchFor values + /// + //////////////////////////////////////////////////////////// + void replace(const String& searchFor, const String& replaceWith); + //////////////////////////////////////////////////////////// /// \brief Get a pointer to the C-style array of characters /// diff --git a/src/SFML/System/String.cpp b/src/SFML/System/String.cpp index f20f6a416..89ce44fa3 100644 --- a/src/SFML/System/String.cpp +++ b/src/SFML/System/String.cpp @@ -281,6 +281,29 @@ std::size_t String::find(const String& str, std::size_t start) const } +//////////////////////////////////////////////////////////// +void String::replace(std::size_t position, std::size_t length, const String& replaceWith) +{ + m_string.replace(position, length, replaceWith.m_string); +} + + +//////////////////////////////////////////////////////////// +void String::replace(const String& searchFor, const String& replaceWith) +{ + std::size_t step = replaceWith.getSize(); + std::size_t len = searchFor.getSize(); + std::size_t pos = find(searchFor); + + // Replace each occurence of search + while (pos != InvalidPos) + { + replace(pos, len, replaceWith); + pos = find(searchFor, pos + step); + } +} + + //////////////////////////////////////////////////////////// const Uint32* String::getData() const {