Skip to content

Instantly share code, notes, and snippets.

@nsubiron
Last active October 21, 2020 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsubiron/2b42c7a0987e65df90d0b6686ef2320b to your computer and use it in GitHub Desktop.
Save nsubiron/2b42c7a0987e65df90d0b6686ef2320b to your computer and use it in GitHub Desktop.
Constexpr methods to handle strings.
#include <cstdint>
#include <string_view>
/// Trim leading chars_to_trim from str.
constexpr std::string_view ltrim(
const std::string_view str,
const std::string_view chars_to_trim = " \t\n\r")
{
if (const auto pos = str.find_first_not_of(chars_to_trim); pos != std::string_view::npos)
{
return str.substr(pos);
}
return str;
}
/// Trim trailing chars_to_trim from str.
constexpr std::string_view rtrim(
const std::string_view str,
const std::string_view chars_to_trim = " \t\n\r")
{
if (const auto pos = str.find_last_not_of(chars_to_trim); pos != std::string_view::npos)
{
return str.substr(0, pos + 1ul);
}
return str;
}
/// Trim leading and trailing chars_to_trim from str.
constexpr std::string_view trim(
const std::string_view str,
const std::string_view chars_to_trim = " \t\n\r")
{
return rtrim(ltrim(str, chars_to_trim), chars_to_trim);
}
/// Find n-th occurrence of c in str. Return str.size() if the given occurrence
/// is not found. find_nth_occurrence<0>(...) always returns zero.
template <size_t N>
constexpr size_t find_nth_occurrence(const std::string_view str, const char c, size_t pos = 0ul)
{
if (N >= str.size())
{
return str.size();
}
size_t count{};
while (count < N)
{
if (pos = str.find(c, pos + 1); pos == std::string_view::npos)
{
return str.size();
}
++count;
}
return pos;
}
/// Split the n-th argument in a list of comma-separated arguments.
///
/// split_nth_argument<0>("a, b, c") == "a"
/// split_nth_argument<1>("a, b, c") == "b"
/// split_nth_argument<2>("a, b, c") == "c"
///
template <size_t N>
constexpr std::string_view split_nth_argument(const std::string_view str, const char c = ',')
{
if constexpr (N == 0ul)
{
return trim(str.substr(0ul, find_nth_occurrence<1ul>(str, c)));
}
else
{
auto begin = std::min(str.size(), 1ul + find_nth_occurrence<N>(str, c));
auto end = find_nth_occurrence<1ul>(str, c, begin);
return trim(str.substr(begin, end - begin));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment