Home > Back-end >  taking only a int from a text with int string in Rust
taking only a int from a text with int string in Rust

Time:10-17

i need to take only the integer from a string like this "Critical: 3\r\n" , note that the value change everytime so i can't search for "3", i need to search for a generic int.

Thanks.

CodePudding user response:

Many ways to do it. There are already some answers. Here is one more approach:

let s = "Critical: 3\r\n";
let s_res = s.split(":").collect::<Vec<&str>>()[1].trim();
println!("s_res = {s_res:?}");   // "3"

In the above code s_res will be a string (&str). To convert that string to an integer, you can do something like this:

let n: isize = s_res.parse().expect("Failed to parse the integer!");    
println!("n = {n}");  // 3

Note that, depending on your needs, you might want to add some extra validations/asserts, in case you expect the pattern might change (for example, the number of colons not to be 1, etc.).

CodePudding user response:

Building on @AlexanderKrauze's comment the most common way to do so is using a regex, which lets you look for any pattern in a String:

let your_text = "Critical: 3\r\n";
let re = Regex::new(r"\d ").unwrap(); // matches any amount of consecutive digits
let result:Option<Match> = re.find(your_text);// returns the match
let number:u32 = result.map(|m| m.as_str().parse::<u32>().unwrap()).unwrap_or(0); // converts to int
print!("{}", number);

would be the code for that. Only one digit is r"\d".

More documentation is found here.

CodePudding user response:

You can use chars to get an iterator over the chars of a string, and then apply filter on that iterator to filter out only digits(is_digit).

fn main() {
    let my_str: String = "Critical: 3\r\n".to_owned();
    let digits: String = my_str.chars().filter(|char| char.is_digit(10)).collect();
    println!("{}", digits)
}
  • Related