Ad
Strings
Mathematics

Make the matching of the operator character more readable

Code
Diff
  • fn math(s: &str) -> i32 {
        // remove whitespace characters so all we have left are digits and the operator
        let math_str: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();
        
        // find the position of the operator character
        let pos: usize = math_str    
            .chars()
            .position(|ch| match ch {
                '+' | '-' | '*' | '/' | '=' => true,
                _ => false
            })
            .expect("invalid operator, expected +, -, *, / or =");
        
        // extract the two numbers from the string
        let num1: i32 = math_str[..pos].parse().unwrap();
        let num2: i32 = math_str[pos + 1..].parse().unwrap();
        
        match &math_str[pos..=pos] {
            "+" => num1 + num2,
            "-" => num1 - num2,
            "*" => num1 * num2,
            "/" => num1 / num2,
            _ => (num1 == num2) as i32,
        }
    }
    • fn math(s: &str) -> i32 {
    • // remove whitespace characters so all we have left are digits and the operator
    • let math_str: String = s.chars().filter(|ch| !ch.is_whitespace()).collect();
    • // find the position of the operator character
    • let pos: usize = math_str
    • .chars()
    • .position(|ch| ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
    • .position(|ch| match ch {
    • '+' | '-' | '*' | '/' | '=' => true,
    • _ => false
    • })
    • .expect("invalid operator, expected +, -, *, / or =");
    • // extract the two numbers from the string
    • let num1: i32 = math_str[..pos].parse().unwrap();
    • let num2: i32 = math_str[pos + 1..].parse().unwrap();
    • match &math_str[pos..pos + 1] {
    • match &math_str[pos..=pos] {
    • "+" => num1 + num2,
    • "-" => num1 - num2,
    • "*" => num1 * num2,
    • "/" => num1 / num2,
    • _ => (num1 == num2) as i32,
    • }
    • }