C++ String resize
This function is employed to adjust the size of the string to k characters in length.
Syntax
To adjust the size of the string object, the syntax used would be:
str.resize(k,c);
Parameters
This function is defined with a pair of arguments.
- k : k represents the count of characters defined in the initial parameter. It adjusts the string to have exactly k characters.
- c : c represents a fresh character to be inserted in any additional space, provided that the length of the string is less than k. This parameter is not mandatory.
If the value of k is less than the length of the string, the string will be truncated to the specified length k by eliminating all characters after the k-th position.
If the value of k exceeds the string's length, the string will be extended to match the specified length of k.
Return value
It does not return any value.
Example 1
When the value of k is less than the length of the given string.
#include<iostream>
using namespace std;
int main()
{
string str= "javacpptutorial";
cout<<"String is :"<<str<<?\n?;
str.resize(4);
cout<<"After resizing, string is "<<str;
return 0;
}
Example 2
When the value of k exceeds the length of the provided string.
#include<iostream>
using namespace std;
int main()
{
string str ="javacpptutorial";
cout<<"String value is :"<<str<<'\n';
str.resize(19,"tutorial");
cout<<"After resizing, string value is :"<<str;
return 0;
}
Output:
String value is javacpptutorial
After resizing, string value is javacpptutorial tutorial