How to Add Leading Zeros to a C++ String?
Last Updated :
05 Mar, 2024
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,
- pos: position where we want to insert the characters.
- count: number of times the character should be inserted.
- chr: character to be inserted.
C++ Program to Add Leading Zeros to a C++ String
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "123" ;
int numZeros = 2;
str.insert(0, numZeros, '0' );
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)
Share your thoughts in the comments
Please Login to comment...