-1

I've have a string like this

"32" or "28", "01", "001"

and I want to parse them to a number. However it should not parse a string that starts with 0.

Currently, I'm doing this

let num = str.parse().unwrap_or(-1);

With this implementation it converts "01" to 1 but I want to force -1 when the string stars with 0.

1
  • 2
    Did you tried using str::starts_with? Commented Nov 10, 2022 at 6:09

1 Answer 1

1

As mentioned in the comments - you could use this:

let num = if s.len() > 1 && s.starts_with('0') {
    -1
} else {
    s.parse().unwrap_or(-1)
};
Sign up to request clarification or add additional context in comments.

4 Comments

"0" is ok, I only want to return -1 when it's something like this "00" or "01"
just add s != "0" && to the condition
@cafce25 yeah it works but I wish there was a more elegant solution
If you're willing to add a dependency you cold use regex crate Regex::new(r"^0\d+").unwrap().is_match(s)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.