std::basic_string_view<CharT,Traits>::remove_prefix

出自cppreference.com
 
 
 
 
constexpr void remove_prefix( size_type n );
(C++17 起)

將視圖起點向前移動 n 個字符。

如果 n > size()true,那麼行為未定義。

(C++26 前)

如果 n > size()true,那麼:

  • 如果實現是硬化實現,那麼就會發生契約違背
  • 如果實現不是硬化實現,那麼行為未定義。
(C++26 起)

參數

n - 要從視圖起始移除的字符數

複雜度

常數。

示例

#include <algorithm>
#include <iostream>
#include <string_view>

using namespace std::literals;

[[nodiscard("纯函数")]]
constexpr std::size_t count_substrings(std::string_view hive, const std::string_view bee)
{
    if (hive.empty() || bee.empty())
        return 0U;
    
    std::size_t buzz{};
    while (bee.size() <= hive.size())
    {
        const auto pos = hive.find(bee);
        if (pos == hive.npos)
            break;
        ++buzz;
        hive.remove_prefix(pos + bee.size());
    }
    return buzz;
}

int main()
{
    std::string str = "   trim me";
    std::string_view v = str;
    v.remove_prefix(std::min(v.find_first_not_of(" "), v.size()));
    std::cout << "字符串:'" << str << "'\n"
              << "视图  :'" << v << "'\n";
    
    constexpr auto hive{"bee buzz bee buzz bee"};
    std::cout << "蜂巢中有 " << count_substrings(hive, "bee") << " 只蜜蜂。\n";
}

輸出:

字符串:'   trim me'
视图  :'trim me'
蜂巢中有 3 只蜜蜂。

參閱

通過向後移動末尾收縮視圖
(公開成員函數) [編輯]