【C++编程】std::string_view
std::string_view
std::string_view 类原型:
template<class CharT, class Traits = std::char_traits<CharT>> class basic_string_view;
构造函数
1. 构造函数原型:
constexpr basic_string_view() noexcept;
|
(1) | (since C++17) |
constexpr basic_string_view( const basic_string_view& other ) noexcept = default;
|
(2) | (since C++17) |
constexpr basic_string_view( const CharT* s, size_type count );
|
(3) | (since C++17) |
constexpr basic_string_view( const CharT* s );
|
(4) | (since C++17) |
1. 示例
1 #include <iostream> 2 #include <string_view> 3 4 int main() 5 { 6 std::string_view sv("123456789", 5); 7 8 for(const auto&c : sv) 9 { 10 std::cout << c << " "; 11 } 12 std::cout << std::endl; 13 14 std::cout << "size() = " << sv.size() << std::endl; 15 std::cout << "data() = " << sv.data() << std::endl; 16 std::cout << "sv.front() = " << sv.front() << std::endl; 17 std::cout << "sv.back() = " << sv.back() << std::endl; 18 return 0; 19 }
输出:
(C++17)
|
shrinks the view by moving its start forward (public member function) |
(C++17)
|
shrinks the view by moving its end backward (public member function) |
1. 示例:
1 #include <iostream> 2 #include <string_view> 3 4 void print(const std::string_view sv) 5 { 6 for (const auto &c : sv) 7 std::cout << c << " "; 8 std::cout << std::endl; 9 } 10 11 int main() 12 { 13 std::string_view sv("123456789", 5); 14 15 print(sv); 16 sv.remove_prefix(1); 17 std::cout << "size() = " << sv.size() << std::endl; 18 std::cout << "data() = " << sv.data() << std::endl; 19 std::cout << "sv.front() = " << sv.front() << std::endl; 20 std::cout << "sv.back() = " << sv.back() << std::endl; 21 return 0; 22 }
输出:
参考资料
1. std::string_view 的用法 【cppreference.com】