public member function
<string>

std::basic_string::resize

void resize (size_type n);void resize (size_type n, charT c);
Resize string
Resizes the string to a length of n characters.

If n is smaller than the current string length, the current value is shortened to its first n character, removing the characters beyond the nth.

If n is greater than the current string length, the current content is extended by inserting at the end as many characters as needed to reach a size of n. If c is specified, the new elements are initialized as copies of c, otherwise, they are value-initialized characters (null characters).

Parameters

n
New string length, expressed in number of characters.
Member type size_type is an unsigned integral type.
c
Character used to fill the new character space added to the string (in case the string is expanded).

Return Value

none

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// resizing string
#include <iostream>
#include <string>

int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';

  std::string::size_type sz = str.size();

  str.resize (sz+2,'+');
  std::cout << str << '\n';

  str.resize (14);
  std::cout << str << '\n';
  return 0;
}

Output:
I like to code in C
I like to code in C++
I like to code


Complexity

Unspecified, but generally up to linear in the new string length.

Iterator validity

Any iterators, pointers and references related to this object may be invalidated.

Data races

The object is modified.

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the basic_string.

If n is greater than max_size, a length_error exception is thrown.
If the type uses the default allocator, a bad_alloc exception is thrown if the function needs to allocate storage and fails.

See also