String Resize Function - C++ Programming Tutorial
C++ Course / Strings / String Resize Function

String Resize Function

BLUF: Mastering String Resize Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: String Resize Function

C++ is renowned for its efficiency. Learn how String Resize Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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.

Example

#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.

Example

#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:

Output

String value is javacpptutorial
After resizing, string value is javacpptutorial tutorial

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience