Dup Ver Goto 📝

StringView_01

PT2/lang/cpp/string cpp string does not exist
To
17 lines, 89 words, 544 chars Page 'StringView_01' does not exist.

Example 1

#include <iostream>
#include <string>
#include <string_view>

int main() {
  char hello[] = "hello world";
  std::string_view a{hello+2,7}; // substring starting at hello[2] and 7 chars long
  std::cout << a << "\n"; // output: 'llo wor'
  hello[6] = 'X';
  std::cout << a << "\n"; // output: 'llo Xor'
}

note that if we had std::string a{hello+2,7}, then this would construct a copy, and so the hello[6] = 'X' would not affect the output on the following line. Views allow us to avoid unnecessary copying of strings.