lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[cpp]:  operator""s  --  <string>

 

 

 

 

1  operator""s :  将一个字符数组字面量转化为【basic_string】类型数据。

  1.1  #include <string>

  1.2  operator""s   :  converts a character array literal to basic_string

  1.3  declare

 

2  e.g.

 1 #include <iostream>
 2 #include <string>
 3  
 4 void print_with_zeros(auto const note, std::string const& s)
 5 {
 6     std::cout << note;
 7     for (const char c : s)
 8         c ? std::cout << c : std::cout << "";
 9     std::cout << " (size = " << s.size() << ")\n";
10 }
11  
12 int main()
13 {
14     using namespace std::string_literals;
15  
16     std::string s1 = "abc\0\0def";
17     std::string s2 = "abc\0\0def"s;
18     print_with_zeros("s1: ", s1);
19     print_with_zeros("s2: ", s2);
20  
21     std::cout << "abcdef"s.substr(1,4) << '\n';
22 }

 

 

3. running

1 g++ -std=c++23 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2 
3 
4 s1: abc (size = 3)
5 s2: abc₀₀def (size = 8)
6 bcde

 

 

4.  Reference

 

  1.  std::literals::string_literals::operator""s  --  https://en.cppreference.com/w/cpp/string/basic_string/operator""s

 

  2.   cpp online tools   --  https://coliru.stacked-crooked.com/

 

posted on 2024-01-16 15:30  lnlidawei  阅读(7)  评论(0编辑  收藏  举报