C++ <string> - resize() Function
The C++ string::resize function is used to resize the string to a length of specified number of characters (n). If n is less than the current string length then the content is reduced to the first n characters of the string. If n is greater than the current string length, then the new characters are inserted at the end of the string. If c is specified, then new characters are initialized with c, else they are value-initialized.
Syntax
void resize (size_t n); void resize (size_t n, char c);
void resize (size_t n); void resize (size_t n, char c);
Parameters
n |
Specify new string length expressed in terms of number of character in it. |
c |
Specify character for the added characters in case that n is greater than current string length. |
Return Value
None.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the string::resize function is used to resize the string str.
#include <iostream> #include <string> using namespace std; int main (){ string str = "Learn Python"; //size of the string is reduced to 6 str.resize(6); //size of the string is expanded to 7 with character 'C' str.resize(7, 'C'); //size of the string is expanded to 9 with character '+' str.resize(9, '+'); cout<<"str contains: "<<str; return 0; }
The output of the above code will be:
str contains: Learn C++
❮ C++ <string> Library