Apply all separators, not only the first one found, ref #518

This commit is contained in:
emeric
2024-09-07 09:34:45 +02:00
parent 39ca55e8fa
commit fc27a4f852
6 changed files with 90 additions and 28 deletions
+44 -16
View File
@@ -97,6 +97,41 @@ namespace lms::core::stringUtils
return res;
}
template<typename StringType>
std::vector<std::string_view> splitString(std::string_view str, std::span<const StringType> separators)
{
std::vector<std::string_view> res;
size_t currentPos{};
while (currentPos < str.size())
{
size_t nextSeparatorPos{ std::string_view::npos };
size_t sepLen{};
for (const std::string_view sep : separators)
{
if (sep.empty())
continue;
size_t found{ str.find(sep, currentPos) };
if (found < nextSeparatorPos)
{
nextSeparatorPos = found;
sepLen = sep.size();
}
}
if (nextSeparatorPos == std::string_view::npos)
break;
res.push_back(str.substr(currentPos, nextSeparatorPos - currentPos));
currentPos = nextSeparatorPos + sepLen;
}
res.push_back(str.substr(currentPos));
return res;
}
} // namespace details
template<>
@@ -129,24 +164,17 @@ namespace lms::core::stringUtils
std::vector<std::string_view> splitString(std::string_view str, std::string_view separator)
{
std::vector<std::string_view> res;
return splitString(str, std::span(&separator, 1));
}
if (separator.empty())
return { str };
std::vector<std::string_view> splitString(std::string_view str, std::span<const std::string_view> separators)
{
return details::splitString(str, separators);
}
size_t pos{};
size_t found{ str.find(separator) };
while (found != std::string_view::npos)
{
res.push_back(str.substr(pos, found - pos));
pos = found + separator.size();
found = str.find(separator, pos);
}
res.push_back(str.substr(pos));
return res;
std::vector<std::string_view> splitString(std::string_view str, std::span<const std::string> separators)
{
return details::splitString(str, separators);
}
std::string joinStrings(std::span<const std::string_view> strings, std::string_view delimiter)