mirror of
https://github.com/bitcoin/bitcoin.git
synced 2025-11-12 15:09:59 +01:00
Extend Split to work with multiple separators
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
#include <span.h>
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace spanparsing {
|
||||
@@ -36,6 +37,30 @@ bool Func(const std::string& str, Span<const char>& sp);
|
||||
*/
|
||||
Span<const char> Expr(Span<const char>& sp);
|
||||
|
||||
/** Split a string on any char found in separators, returning a vector.
|
||||
*
|
||||
* If sep does not occur in sp, a singleton with the entirety of sp is returned.
|
||||
*
|
||||
* Note that this function does not care about braces, so splitting
|
||||
* "foo(bar(1),2),3) on ',' will return {"foo(bar(1)", "2)", "3)"}.
|
||||
*/
|
||||
template <typename T = Span<const char>>
|
||||
std::vector<T> Split(const Span<const char>& sp, std::string_view separators)
|
||||
{
|
||||
std::vector<T> ret;
|
||||
auto it = sp.begin();
|
||||
auto start = it;
|
||||
while (it != sp.end()) {
|
||||
if (separators.find(*it) != std::string::npos) {
|
||||
ret.emplace_back(start, it);
|
||||
start = it + 1;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
ret.emplace_back(start, it);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/** Split a string on every instance of sep, returning a vector.
|
||||
*
|
||||
* If sep does not occur in sp, a singleton with the entirety of sp is returned.
|
||||
@@ -46,18 +71,7 @@ Span<const char> Expr(Span<const char>& sp);
|
||||
template <typename T = Span<const char>>
|
||||
std::vector<T> Split(const Span<const char>& sp, char sep)
|
||||
{
|
||||
std::vector<T> ret;
|
||||
auto it = sp.begin();
|
||||
auto start = it;
|
||||
while (it != sp.end()) {
|
||||
if (*it == sep) {
|
||||
ret.emplace_back(start, it);
|
||||
start = it + 1;
|
||||
}
|
||||
++it;
|
||||
}
|
||||
ret.emplace_back(start, it);
|
||||
return ret;
|
||||
return Split<T>(sp, std::string_view{&sep, 1});
|
||||
}
|
||||
|
||||
} // namespace spanparsing
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <locale>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
[[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, char sep)
|
||||
@@ -21,6 +22,11 @@
|
||||
return spanparsing::Split<std::string>(str, sep);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::vector<std::string> SplitString(std::string_view str, std::string_view separators)
|
||||
{
|
||||
return spanparsing::Split<std::string>(str, separators);
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::string_view TrimStringView(std::string_view str, std::string_view pattern = " \f\n\r\t\v")
|
||||
{
|
||||
std::string::size_type front = str.find_first_not_of(pattern);
|
||||
|
||||
Reference in New Issue
Block a user