pastebin

Paste Search Dynamic
Recent pastes
string substr
  1. #include <string>
  2. #include <iostream>
  3.  
  4. int main()
  5. {
  6.     std::string a = "0123456789abcdefghil";
  7.  
  8.     // count is npos, returns [pos, size())
  9.     std::string sub1 = a.substr(10);
  10.     std::cout << sub1 << 'n';
  11.  
  12.     // both pos and pos+count are within bounds, returns [pos, pos+count)
  13.     std::string sub2 = a.substr(5, 3);
  14.     std::cout << sub2 << 'n';
  15.  
  16.     // pos is within bounds, pos+count is not, returns [pos, size())
  17.     std::string sub4 = a.substr(a.size()-3, 50);
  18.     // this is effectively equivalent to
  19.     // std::string sub4 = a.substr(17, 3);
  20.     // since a.size() == 20, pos == a.size()-3 == 17, and a.size()-pos == 3
  21.  
  22.     std::cout << sub4 << 'n';
  23.  
  24.     try {
  25.         // pos is out of bounds, throws
  26.         std::string sub5 = a.substr(a.size()+3, 50);
  27.         std::cout << sub5 << 'n';
  28.     } catch(const std::out_of_range& e) {
  29.         std::cout << "pos exceeds string sizen";
  30.     }
  31. }
Parsed in 0.013 seconds