Skip to content
Related Articles

Related Articles

Remove Trailing Zeros From string in C++
  • Difficulty Level : Medium
  • Last Updated : 31 May, 2017

Given a string of digits, remove trailing zeros from it.

Examples:

Input : 00000123569
Output : 123569

Input : 000012356090
Output : 12356090

1) Count trailing zeros.
2) Use string erase function to remove characters equal to above count.

Below is C++ implementation.






// C++ program to remove trailing/preceding zeros
// from a given string
#include<iostream>
using namespace std;
  
string removeZero(string str)
{
    // Count trailing 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

This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :