我有兴趣查看字符串的一部分。我在下面有一个示例代码。实际上我有兴趣查看字符串的子字符串,例如从索引 1 到 5 或 0 到 7 左右。我有 .substr()
,但我想避免复制。我该怎么做。
#include <iostream>
#include <string>
#include <experimental/string_view>
int main()
{
std::string name;
name = "Hello world";
std::experimental::string_view name_v (name);
std::cout << "string view, " << name_v << "!\n";
}
最佳答案
只需使用 std::experimental::string_view::substr它创建了一个新的 string_view无需复制任何字符串本身:
std::string name = "Hello world";
std::experimental::string_view name_v (name);
std::cout << "string view, " << name_v << "!\n";
auto sub_v = name_v.substr(1, 4); // creates a new string_view
std::cout << "sub view, " << sub_v << '\n';
关于c++ - C++中的字符串 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42038549/