In C++, std::string::resize() sets the string to a new length.
Growing pads with '\\0' (or a fill char). Shrinking cuts the end. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Pass the new size, and optionally a fill character.
C++
s.resize(10);
s.resize(10, '*');
Call
What it does
s.resize(n)
Set size to n; new chars are char() which is a null character.
s.resize(n, ch)
Set size to n; new chars are ch.
Default fill is a null character, which can look invisible when printing. Prefer an explicit fill when you want visible padding.
Library declarations
C++
void resize(size_type n);
void resize(size_type n, char c);
Parameters
Parameter
Description
n
New size.
c
Optional fill character used when growing.
Return Value
Return Value
Description
void
No return value.
C++ Examples
Example 1 — Resize Larger
Pad with stars.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "hi";
s.resize(5, '*');
std::cout << s << '\\n';
return 0;
}
Output
hi***
How It Works
Size was 2.
Resize to 5 adds three '*'.
Result is "hi***".
Example 2 — Resize Smaller
Truncate the end.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "abcdef";
s.resize(3);
std::cout << s << '\\n';
return 0;
}