Remove Trailing Zeros from string in C++


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”

Algorithm

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

#include<iostream>
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') {
      num++;
   }
   my_str.erase(0, num); //erase characters from 0 to i index
   cout << "Number without Trailing Zeros :" << my_str;
}

Output

Number with Trailing Zeros :000023500124
Number without Trailing Zeros :23500124

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements