String Views

Modify string through string_view

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved