Open In App

Remove Leading Zeros From String in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program to remove leading zeros
// from a given string
#include <iostream>
  
using namespace std;
  
string removeZero(string str)
{
    // Count leading zeros
    int i = 0;
    while (str[i] == '0')
        i++;
  
    // The erase function removes i characters
    // from given index (0 here)
    str.erase(0, i);
  
    return str;
}
  
// Driver code
int main()
{
    string str;
    str = "00000123569";
    str = removeZero(str);
    cout << str << endl;
    return 0;
}


Output

123569

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++




// C++ Program to remove leading zeros 
// with the help of stoi() function
#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
Previous
Next
Share your thoughts in the comments
Similar Reads