String Views

Concatenate string_views

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

Abstract art representing computer programming

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.

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:

  • 124 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