Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,919 questions

51,852 answers

573 users

How to extract the number from the end of a string in Rust

2 Answers

0 votes
use regex::Regex;

fn extract_last_number(s: &str) -> i32 {
    let re = Regex::new(r"\D+").unwrap();
    
    let parts: Vec<&str> = re.split(s).collect();
    
    parts.last().unwrap().parse::<i32>().unwrap()
}

fn main() {
    let s = "rust 84 programming1092";
    
    let n = extract_last_number(s);
    
    println!("{}", n);
}

  
  
  
/*
run:
  
1092
  
*/

 



answered Aug 17, 2024 by avibootz
0 votes
fn extract_last_number(s: &str) -> i32 {
    let mut i = s.len();

    while i > 0 && s.chars().nth(i - 1).unwrap().is_digit(10) {
        i -= 1;
    }

    s[i..].parse::<i32>().unwrap()
}

fn main() {
    let s = "rust 84 programming1092";

    let n = extract_last_number(s);

    print!("{}", n);
}

  
  
  
/*
run:
  
1092
  
*/

 



answered Aug 17, 2024 by avibootz
edited Aug 17, 2024 by avibootz
...