String Views

Convert string_view to string

How do I convert a std::string_view back to a std::string?

Abstract art representing computer programming

To convert a std::string_view back to a std::string, you need to create a new std::string object and pass the std::string_view to its constructor.

This is necessary because std::string_view provides a view over a string without owning the data, while std::string owns and manages the data.

Here's an example:

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

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

  std::cout << str;
}
Hello, world

In this example, std::string str{view}; constructs a new std::string by copying the data from the std::string_view. This way, str owns its data, and you can modify it independently of the original view.

Remember, constructing a std::string from a std::string_view involves copying the data, which can be expensive for large strings. Always consider the performance implications in your specific use case.

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