What is std::basic_string::copy in C/C++?

The basic_string is the generalization of class string for any character type. The string is an instantiation of the basic_string class that represents sequences of characters.

The basic_string class provides a list of methods that are used for various operations. One of them is std::basic_string::copy. std::basic_string::copy copies a sequence of characters from a given string and returns the copied characters as an array.

Parameters

As seen in the diagram, the std::basic_string::copy method accepts three parameters.

  1. buffer: represents a pointer to an array of characters that contains the copied characters from the given string.
  2. len: an integer that specifies the number of characters to be copied.
  3. pos: an integer that specifies the position of the first character to be copied.

Given that we have a string named str, the syntax of std::basic_string::copy is:

str.copy(char* buffer, len, pos);

Value returned

std::basic_string::copy returns the characters that are stored into the array and pointed to by the buffer (pointer).

Note: The length of the array pointed to by the buffer should be long enough to store the copied characters; otherwise, some weird output may appear. Also, the value given to the pos parameter must be less than or equal to the length of the original string; otherwise, it will give the std::out_of_range exception.

Code

Here, we have an array named buffer that contains the copied characters from the given string. As you can see, the buffer's size is comparatively more than the number of characters that we want to copy.

Upon executing this code, the characters from position 8 to position 18(10 + 8) will be copied into a buffer and printed on the terminal.

#include <iostream>
#include <string>
int main ()
{
char buffer[20];
std::string str ("What is std::basic_string::copy in C/C++?");
str.copy(buffer, 10, 8);
std::cout << "Output: " << buffer;
return 0;
}

Now, we will set the size of the array to less than the number of characters that we will copy. Any guess what the output will be?

#include <iostream>
#include <string>
int main ()
{
char buffer[10];
std::string str ("What is std::basic_string::copy in C/C++?");
str.copy(buffer, 14, 8);
std::cout << "Output: " << buffer;
return 0;
}

Finally, we will set the pos parameter to greater than the length of the string. This time, I think we can easily guess the output.

#include <iostream>
#include <string>
int main ()
{
char buffer[20];
std::string str ("What is std::basic_string::copy in C/C++?");
str.copy(buffer, 10, 42);
std::cout << "Output: " << buffer;
return 0;
}

That’s all for std::basic_string::copy. I hope this shot has helped you understand this method.

This method doesn’t assign a null character at the end of the string on its own, so if you need one, you have to append the null character yourself.

You can connect with me on Twitter for any discussions.

Thanks for reading.

Adios!

Free Resources