Remove Leading Zeros From String in C++

Last Updated : 22 Aug, 2026

Given a string containing digits, the task is to remove all leading zeros while preserving the remaining digits. This can be done either by modifying the string directly or by converting it into an integer.

  • The erase() approach preserves the string and works with very large numeric strings.
  • The stoi() approach converts the string to an integer before converting it back to a string.

Examples:

Input : 00000123569
Output : 123569

Input : 000012356090
Output : 12356090

Approaches to Remove Leading Zeros

The following two approaches can be used:

1. Using the erase() Function

The erase() function can remove the leading zeros directly from the original string.

  • Find the first character that is not '0'.
  • Remove all characters before that position using erase().
  • If the string contains only zeros, return "0".
CPP
#include <iostream>
#include <string>
using namespace std;

string removeLeadingZeros(string str)
{
    size_t pos = str.find_first_not_of('0');

    if (pos == string::npos)
        return "0";

    str.erase(0, pos);

    return str;
}

int main()
{
    string str = "00000123569";

    cout << removeLeadingZeros(str) << '\n';

    return 0;
} 

Output
123569

Explanation

  • find_first_not_of('0') finds the position of the first character that is not 0.
  • If the string contains only zeros, string::npos is returned, so the function returns "0".
  • erase(0, pos) removes all the leading zeros from the string.
  • For "00000123569", the output is 123569.

This approach works directly on the string, so it does not require converting the value to an integer.

2. Using stoi() and to_string()

The stoi() function converts a numeric string into an integer. Converting the string to an integer automatically removes leading zeros from its numeric representation.

The resulting integer can then be converted back into a string using to_string().

C++
#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str = "00000123569";

    int num = stoi(str);
    str = to_string(num);

    cout << str << '\n';

    return 0;
} 

Output
123569

Explanation

  • string str = "00000123569"; creates a string containing leading zeros.
  • stoi(str) converts the string into an integer, so the leading zeros are removed.
  • to_string(num) converts the integer back into a string.

Note: stoi() should be used only when the value fits within the range of int. For very large numeric strings, use the erase() approach instead.

Comment