Ad
Strings
Mathematics
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| ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
            .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] {
            "+" => num1 + num2,
            "-" => num1 - num2,
            "*" => num1 * num2,
            "/" => num1 / num2,
            _ => (num1 == num2) as i32,
        }
    }
    • fn math(s: &str) -> i32 {
    • // first remove whitespace characters so all we have left are digits and the operator
    • let num_str: String = s.chars().filter(|ch| *ch != ' ').collect();
    • // 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();
    • // extract the operator character
    • let pos: usize = num_str
    • // find the position of the operator character
    • let pos: usize = math_str
    • .chars()
    • .position(|ch| ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '=')
    • .expect("invalid operator, expected '+, -, *, / or =");
    • let operator: char = num_str
    • .chars()
    • .nth(pos)
    • .unwrap();
    • .expect("invalid operator, expected +, -, *, / or =");
    • // extract the two numbers from the string
    • let num1: i32 = num_str.get(0..pos).unwrap().parse().unwrap();
    • let num2: i32 = num_str.get(pos + 1..).unwrap().parse().unwrap();
    • let num1: i32 = math_str[..pos].parse().unwrap();
    • let num2: i32 = math_str[pos + 1..].parse().unwrap();
    • match operator {
    • '+' => num1 + num2,
    • '-' => num1 - num2,
    • '*' => num1 * num2,
    • '/' => num1 / num2,
    • match &math_str[pos..pos + 1] {
    • "+" => num1 + num2,
    • "-" => num1 - num2,
    • "*" => num1 * num2,
    • "/" => num1 / num2,
    • _ => (num1 == num2) as i32,
    • }
    • }