Remove Trailing Zeros from string in C++

C++Server Side ProgrammingProgramming

IN this program we will see how to remove the trailing zeros from a string in C++. Sometimes some string may contain trailing zeros like "00023054". After executing this program, it will return "23054" only. The initial zeros are removed.

Input: A string with trailing zeros “000023500124”
Output: “23500124”


Step 1: Get the string
Step 2: Count number of trailing zeros n
Step 3: Remove n characters from the beginning
Step 4: return remaining string.

Example Code

 Live Demo

using namespace std;
main() {
   string my_str = "000023500124";
   int num = 0;
   cout << "Number with Trailing Zeros :" << my_str << endl;
   //count number of trailing zeros in the string
   while(my_str[num] == '0') {
   my_str.erase(0, num); //erase characters from 0 to i index
   cout << "Number without Trailing Zeros :" << my_str;


Number with Trailing Zeros :000023500124
Number without Trailing Zeros :23500124
Published on 28-Mar-2019 16:40:13