C++ string resize() Function
Example
Make a string shorter, and then longer:
string txt = "Hello World!";
txt.resize(5);
cout << txt << "\n";
txt.resize(8, '!');
cout << txt;
Definition and Usage
The resize() function changes the number of characters in a string.
If the new size is smaller, characters are removed from the end. If the new size is larger, new characters are added to the end. You can choose which character to add. If you do not choose, the null character (\0) is added.
The resize function is defined in the <string> header file.
Syntax
string.resize(size_t size);
string.resize(size_t size, char c);
The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| size | Required. The new number of characters. |
| c | Optional. The character to add if the string gets longer. Default is the null character (\0). |
Technical Details
| Returns: | Nothing (void). |
|---|
Related Pages
Read more about strings in our String Tutorial.