Concatenate string_views

Is it possible to concatenate two std::string_view objects?

Concatenating two std::string_view objects directly is not possible because std::string_view is a non-owning, read-only view of a string.

However, you can achieve concatenation by creating a new std::string that combines the contents of both std::string_view objects.

Here's how you can do it:

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

int main() {
  std::string_view view1{"Hello, "};
  std::string_view view2{"world!"};

  // Create a new std::string that
  // concatenates view1 and view2
  std::string combined{view1};
  combined += view2;  

  std::cout << combined;
}
Hello, world!

Using std::stringstream

Another approach involves using std::stringstream for concatenation:

#include <iostream>
#include <sstream>
#include <string_view>

int main() {
  std::string_view view1{"Hello, "};
  std::string_view view2{"world!"};

  std::stringstream ss;
  ss << view1 << view2;  

  std::string combined = ss.str();
  std::cout << combined;
}
Hello, world!

Custom Function

For more flexibility, you can write a function to concatenate std::string_view objects:

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

std::string concatenate(
  std::string_view a, std::string_view b
) {
  return std::string{a} + std::string{b};  
}

int main() {
  std::string_view view1{"Hello, "};
  std::string_view view2{"world!"};

  std::string combined =
    concatenate(view1, view2);
  std::cout << combined;
}
Hello, world!

While std::string_view itself doesn't support concatenation, combining them into a new std::string is straightforward and provides the desired result.

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?
Modify string through string_view
Can I modify the contents of a string through a std::string_view?
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?
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