Namespaces
Variants

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

From cppreference.net
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("a pure function")]]
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 << "String: '" << str << "'\n"
              << "View  : '" << v << "'\n";
    constexpr auto hive{"bee buzz bee buzz bee"};
    std::cout << "There are " << count_substrings(hive, "bee") << " bees in this hive.\n";
}

输出:

String: '   trim me'
View  : 'trim me'
There are 3 bees in this hive.

参见

通过向后移动其末端来缩小视图
(公开成员函数)