使用http://en.cppreference.com/w/cpp/string/basic_string_view作为参考,我认为没有办法更优雅地做到这一点:
std::string s = "hello world!";
std::string_view v = s;
v = v.substr(6, 5); // "world"
Run Code Online (Sandbox Code Playgroud)
更糟糕的是,天真的方法是一个陷阱,并留下v暂时的悬挂参考:
std::string s = "hello world!";
std::string_view v(s.substr(6, 5)); // OOPS!
Run Code Online (Sandbox Code Playgroud)
我似乎记得有些东西可能会添加到标准库中以返回子字符串作为视图:
auto v(s.substr_view(6, 5));
Run Code Online (Sandbox Code Playgroud)
我可以想到以下解决方法:
std::string_view(s).substr(6, 5);
std::string_view(s.data()+6, 5);
// or even "worse":
std::string_view(s).remove_prefix(6).remove_suffix(1);
Run Code Online (Sandbox Code Playgroud)
坦率地说,我认为这些都不是很好.现在我能想到的最好的事情是使用别名来简化事情.
using sv = std::string_view;
sv(s).substr(6, 5);
Run Code Online (Sandbox Code Playgroud) 我有一个获取std::string_view和使用函数的方法,它以null终止的字符串作为参数.例如:
void stringFunc(std::experimental::string_view str) {
some_c_library_func(/* Expects null terminated string */);
}
Run Code Online (Sandbox Code Playgroud)
问题是,处理这种情况的正确方法是什么?是str.to_string().c_str()唯一的选择吗?我真的想std::string_view在这个方法中使用,因为我在其中传递了不同类型的字符串.