at54321
at54321

Reputation: 11728

Remove leading zeroes from a string

What is the simplest way to remove all leading zeroes from a string?

Here is something I came up with:

let mut chars = original_str.chars();
let mut res = chars.as_str();
while chars.next() == Some('0') {
    res = chars.as_str();
}

Is there something better, in terms of brevity and/or performance?

Upvotes: 5

Views: 1748

Answers (1)

Netwave
Netwave

Reputation: 42716

Use str::trim_start_matches

fn main() {
    assert_eq!("00foo1bar11".trim_start_matches('0'), "foo1bar11");
}

Playground

Upvotes: 9

Related Questions