public member function
std::string::resize
<string>
void resize ( size_t n, char c );
void resize ( size_t n );
Resize string
Resizes the string content to
n characters.
If
n is smaller than the current length of the string, the content is reduced to its first
n characters, the rest being dropped.
If
n is greater than the current length of the string, the content is expanded by appending as many instances of the
c character as needed to reach a size of
n characters.
The second version, actually calls:
resize(n,char()), so when a string is resized to a greater size without passing a second argument, the new character positions are filled with the default value of a
char, which is the null character.
Parameters
- n
- New size for the string, expressed in characters.
size_t is an unsigned integral type.
- c
- Character to be used to fill any additional character space in the string.
Return Value
none
If the requested size is greater than the maximum size (
string::max_size) a
length_error exception is thrown.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// resizing string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
size_t sz;
string str ("I like to code in C");
cout << str << endl;
sz=str.size();
str.resize (sz+2,'+');
cout << str << endl;
str.resize (14);
cout << str << endl;
return 0;
}
|
Output:
I like to code in C
I like to code in C++
I like to code
|
Basic template member declaration
( basic_string<charT,traits,Allocator> )
1 2 3
|
typedef typename Allocator::size_type size_type;
void resize( size_type n, charT c );
void resize( size_type n );
|
See also
- string::size
- Return length of string (public member function)
- string::clear
- Clear string (public member function)
- string::max_size
- Return maximum size of string (public member function)