Open In App

How to Add Leading Zeros to a C++ String?

In C++, a string data structure is used to store the sequence of characters. These characters can be letters, symbols, or numbers. In this article, we will learn how to add leading zeros to a string that represents some numeric data in C++.

Examples:



Input: 
str="123" N=2

Output: "00123"

Explanation: 2 zeros (N) are added at the starting of given string str which is 123.

Add Leading Zeros to String in C++

To add leading Zeros to a string in C++, we can use the string::insert() function that can add the given characters at the given position in the string.

Syntax of string::insert()

stringName.insert(pos, count, chr);

Here,



C++ Program to Add Leading Zeros to a C++ String




// C++ Program to illustrate how to add leading zeroes to a
// string representing a numerica data
#include <iostream>
#include <string>
using namespace std;
  
int main()
{
    // Original string
    string str = "123";
  
    // Number of leading zeros to add
    int numZeros = 2;
  
    // Adding leading zeros to the string
    str.insert(0, numZeros, '0');
  
    // Printing the string after adding leading zeros
    cout << "String after adding leading zeros: " << str
         << endl;
  
    return 0;
}

Output
String after adding leading zeros: 00123

Time complexity:O(M + N), where M is the number of Zeroes and N is the length of the string.
Auxiliary Space: O(M)

Article Tags :