fix(Core/Utilites): improve acore::String::Trim (#4704)

- Improve `acore::String::Trim`
- Delete `acore::String::Reduce`
- Skip line comment #4748
This commit is contained in:
Kargatum
2021-03-09 21:02:45 +07:00
committed by GitHub
parent ddc18fa6c2
commit 60d684282b
3 changed files with 31 additions and 35 deletions

View File

@@ -4,37 +4,31 @@
*/
#include "StringFormat.h"
#include <locale>
// Taken from https://stackoverflow.com/a/1798170
std::string acore::String::Trim(std::string const& str, std::string_view whitespace /*= " \t"*/)
template<class Str>
Str acore::String::Trim(const Str& s, const std::locale& loc /*= std::locale()*/)
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return ""; // no content
typename Str::const_iterator first = s.begin();
typename Str::const_iterator end = s.end();
auto const strEnd = str.find_last_not_of(whitespace);
auto const strRange = strEnd - strBegin + 1;
while (first != end && std::isspace(*first, loc))
++first;
return str.substr(strBegin, strRange);
if (first == end)
return Str();
typename Str::const_iterator last = end;
do
--last;
while (std::isspace(*last, loc));
if (first != s.begin() || last + 1 != end)
return Str(first, last + 1);
return s;
}
std::string acore::String::Reduce(std::string const& str, std::string_view fill /*= " "*/, std::string_view whitespace /*= " \t"*/)
{
// trim first
auto result = Trim(str, whitespace);
// replace sub ranges
auto beginSpace = result.find_first_of(whitespace);
while (beginSpace != std::string::npos)
{
const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
const auto range = endSpace - beginSpace;
result.replace(beginSpace, range, fill);
const auto newStart = beginSpace + fill.length();
beginSpace = result.find_first_of(whitespace, newStart);
}
return result;
}
// Template Trim
template std::string acore::String::Trim<std::string>(const std::string& s, const std::locale& loc /*= std::locale()*/);