我有兴趣查看字符串的一部分。我在下面有一个示例代码。实际上我有兴趣查看字符串的子字符串,例如索引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";
}
答案 0 :(得分:2)
只需使用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';