C++ string copy() Function
Example
Copy the first 5 characters of a string into a char array:
string txt = "Hello World!";
char letters[6] = {};
txt.copy(letters, 5);
cout << letters;
Definition and Usage
The copy() function copies characters from a string into a char array.
You choose how many characters to copy, and the position to start from.
The copy function is defined in the <string> header file.
Note: copy() does not add a null character (\0) at the end. In the example, {} fills the array with null characters first, so cout knows where the text ends.
Syntax
string.copy(char* array, size_t length, size_t start);
The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| array | Required. The char array to copy the characters to. It must be big enough. |
| length | Required. The number of characters to copy. If the string is shorter, fewer characters are copied. |
| start | Optional. The position of the first character to copy. Default is 0. |
Technical Details
| Returns: | The number of characters that were copied, as a size_t. |
|---|
Related Pages
Read more about strings in our String Tutorial.