Shane Hart
Shane Hart

Reputation: 27

Remove leading zeros from multiple numbers in string? [C++]

Let's say I have a string that contains "00001234 00002345", but I want to output it at "1234 2345". How would I go about that?

    str.erase(0, str.find_first_not_of('0'));

This removes the 0's from the first number, but not any preceding number.

Upvotes: 1

Views: 722

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You can use a \b0+ regex (it matches 0 symbols after a non-word character, i.e. [a-zA-Z0-9_]) if you are interested in a regex solution:

std::string input("00001234 00002345");
std::regex rgx(R"(\b0+)");
std::cout << std::regex_replace(input, rgx, "");
// => 1234 2345

See IDEONE demo

Note that raw string literals allow us to use single backslashes to escape regex metacharacters.

Upvotes: 2

Related Questions