Modify string through string_view

Can I modify the contents of a string through a std::string_view?

No, you cannot modify the contents of a string through a std::string_view. std::string_view is designed to provide a read-only view of a string or a portion of a string.

It does not own the data, and it does not allow modification of the underlying string.

If you need to modify the string, you should work with a std::string or another modifiable string type. Here's an example to illustrate this:

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

void modifyString(std::string& str) {
  str[0] = 'h';  
}

int main() {
  std::string original{"Hello, world"};
  std::string_view view{original};

  // Trying to modify through string_view
  // will result in an error:
  // view[0] = 'h'; 

  modifyString(original);  
  std::cout << original;
}
hello, world

In this example, modifyString(original); successfully changes the first character of the std::string from H to h.

Attempting to modify the string through std::string_view would result in a compilation error because std::string_view does not support modification.

String Views

A practical introduction to string views, and why they should be the main way we pass strings to functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Convert string_view to string
How do I convert a std::string_view back to a std::string?
wstring_view vs string_view
How does std::wstring_view differ from std::string_view?
string_view vs const string&
When should I use std::string_view instead of const std::string&?
Handle dangling string_view
How do I safely handle dangling std::string_view?
string_view performance benefits
How does std::string_view improve performance compared to std::string?
Concatenate string_views
Is it possible to concatenate two std::string_view objects?
string_view vs span
What is the difference between std::string_view and std::span?
string_view in multithreading
Can I use std::string_view in multithreaded applications?
string_view to C-style string
How do I convert a std::string_view to a C-style string safely?
string_view and Encoding
How does std::string_view interact with different character encodings?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant