Remove Trailing Zeros From string in C++
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; } |
chevron_right
filter_none
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.
Recommended Posts:
- Remove duplicates from a string using STL in C++
- Remove all consecutive duplicates from a string using STL in C++
- Remove Duplicate/Repeated words from String
- Removing elements between the two zeros
- std::remove, std::remove_if in c++
- list remove() function in C++ STL
- Remove comments from a given C/C++ program
- Remove duplicate elements in an Array using STL in C++
- Difference between std::remove and vector::erase for vectors
- Check if a string can be formed from another string using given constraints
- std::string::append vs std::string::push_back() vs Operator += in C++
- std::string::remove_copy(), std::string::remove_copy_if() in C++
- std::string::replace , std::string::replace_if in C++
- std::string::replace_copy(), std::string::replace_copy_if in C++
- list::remove() and list::remove_if() in C++ STL



