Remove Leading Zeros From String in C++
Given a string of digits, remove leading zeros from it.
Examples:
Input : 00000123569
Output : 123569
Input : 000012356090
Output : 12356090
In this article, we will use two string functions i.e, string erase and stoi() to remove leading zeros from the string.
1. Using String Erase Function
- Count trailing zeros.
- Use the string erase function to remove characters equal to the above count. Below is C++ implementation.
CPP
#include <iostream>
using namespace std;
string removeZero(string str)
{
int i = 0;
while (str[i] == '0' )
i++;
str.erase(0, i);
return str;
}
int main()
{
string str;
str = "00000123569" ;
str = removeZero(str);
cout << str << endl;
return 0;
}
|
2. Using Stoi() Method
stoi() function in C++ is used to convert the given string into an integer value. It takes a string as an argument and returns its value in integer form. We can simply use this method to convert our string to an integer value which will remove the leading zeros.
s to i()
| | |___ integer
| |_______ to
|__________ String
C++
#include <iostream>
using namespace std;
int main()
{
string str;
str = "00000123569" ;
int num = stoi(str);
str = to_string(num);
cout << "String after removing leading zeros is: "
<< str << endl;
return 0;
}
|
Output
String after removing leading zeros is: 123569
Last Updated :
14 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...