![](/img/trans.png)
[英]How to use std::string_view::remove_prefix() on a constexpr string_view
[英]Best way to remove string prefix from std::string_view?
從 C++20 開始, string_view
具有remove_prefix
但它是“錯誤的”(對我的用例來說是錯誤的)。 它以字符數作為參數,而不是前綴(類似字符串的東西)。
我有這段代碼,但我想知道是否有更好的方法來做我想做的事情(請注意,我的代碼關心是否刪除了前綴,所以我返回布爾值):
static bool Consume(std::string_view& view, const std::string_view prefix)
{
if (view.starts_with(prefix))
{
view.remove_prefix(prefix.size());
return true;
}
return false;
}
注意:我知道我可以返回optional<string_view>
而不是 bool + out arg,但這是一個不同的討論風格,我主要關心的是有類似不存在的東西
bool /*prefix removed*/string_view::remove_prefix(string_view prefix);
注意2:標記此 C++17 因為那是string_view
“到達”時,我對任何 C++20 替代品都很好。
我最關心的是擁有不存在的東西
bool /*prefix removed*/string_view::remove_prefix(string_view prefix);
事實上,這樣的 function 不在標准庫中。 但是您現在已經編寫了這樣的 function,因此您的 function 是執行您想要的操作的更好方法。
如果您對不同的設計持開放態度,我建議您采用以下替代方案:
constexpr std::string_view
remove_prefix(std::string_view sv, std::string_view prefix) noexcept
{
return sv.starts_with(prefix)
? sv.substr(prefix.size())
: sv;
}
// usage
string_view no_prefix = remove_prefix(view, prefix);
bool was_removed = no_prefix.size() != view.size();
或返回 class:
struct modify_result {
std::string_view result;
bool modified;
};
constexpr modify_result
remove_prefix(std::string_view sv, std::string_view prefix) noexcept
{
return sv.starts_with(prefix)
? modify_result{sv.substr(prefix.size()), true}
: modify_result{sv, false};
}
// usage
auto [no_prefix, was_removed] = remove_prefix(view, prefix);
我並不是說這些更適合您的用例。 這些只是可能適用於不同用例的替代解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.