How to check if String exists in a vec?

Hello guys, I wish to make a tiny command-line app that takes input from a user, checks if that String exists in an array, and then returns "User found" if the String exists and "Not found" if the String doesn't exist in that array.

Right now, I'm doing this :

use std::io;


fn main()  {

    println!("Enter your name :");
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");


    if input.to_string().contains("Andy") {
        println!("User found!")
    }

    else if input.to_string().contains("John") {
        println!("User found!")
    }

    else {
        println!("Sorry, user not found!")
    }


}

My aim is rather than checking each in a separate if block, it be checked from this array:

let array = vec!["Andy", "John"];

Thanks.

This would do the equivalent of what you did, I think.

use std::io;

fn main()  {
    println!("Enter your name :");
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");

    let array = vec!["Andy", "John"];
    if array.iter().any(|e| input.contains(e)) {
        println!("User found!")
    } else {
        println!("Sorry, user not found!")
    }
}

Source:
https://doc.rust-lang.org/std/primitive.slice.html#method.contains

1 Like

(Side note: You don't need to call .to_string() on input because it is already a string.)

1 Like

Thank you so much

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.