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, worldIn 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