[wpiutil] Add remove_prefix() and remove_suffix() (#6118)

This commit is contained in:
Joseph Eng
2024-06-04 21:01:52 -07:00
committed by GitHub
parent 8def7b2222
commit d6b66bfa55
12 changed files with 131 additions and 68 deletions

View File

@@ -357,6 +357,32 @@ inline bool contains_lower(std::string_view str, const char* other) noexcept {
return find_lower(str, other) != std::string_view::npos;
}
/**
* Return an optional containing @p str but with @p prefix removed if the string
* starts with the prefix. If the string does not start with the prefix, return
* an empty optional.
*/
constexpr std::optional<std::string_view> remove_prefix(std::string_view str, std::string_view prefix) noexcept {
if (str.starts_with(prefix)) {
str.remove_prefix(prefix.size());
return str;
}
return std::nullopt;
}
/**
* Return an optional containing @p str but with @p suffix removed if the
* string ends with the suffix. If the string does not end with the suffix,
* return an empty optional.
*/
constexpr std::optional<std::string_view> remove_suffix(std::string_view str, std::string_view suffix) noexcept {
if (str.ends_with(suffix)) {
str.remove_suffix(suffix.size());
return str;
}
return std::nullopt;
}
/**
* Return a string_view equal to @p str but with the first @p n elements
* dropped.