Search code examples
loopscharacterlinerustcontains

Read lines from file, iterate over each line and each character in that line


I need to read a file, get each line, iterate over each line and check if that line contains any character from "aeiuo" and if it contains at least 2 of the characters "äüö".

Is this code idiomatic Rust? How do I check for several characters in a String?

My attempt so far with some Google and code stealing:

use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    // Create a path to the desired file
    let path = Path::new("foo.txt");
    let display = path.display();

    // Open the path in read-only mode, returns `io::Result<File>`
    let file = match File::open(&path) {
        // The `description` method of `io::Error` returns a string that describes the error
        Err(why) => panic!("couldn't open {}: {}", display, Error::to_string(&why)),
        Ok(file) => file,
    };

    // Collect all lines into a vector
    let reader = BufReader::new(file);
    let lines: Vec<_> = reader.lines().collect();

    for l in lines {
        if (l.unwrap().contains("a")) {
            println!("here is a");
        }
    }
}

(Playground link)


Solution

  • This works:

    use std::error::Error;
    use std::fs::File;
    use std::io::BufReader;
    use std::io::prelude::*;
    use std::path::Path;
    
    fn is_vowel(x: &char) -> bool {
        "aAeEiIoOuU".chars().any(|y| y == *x)
    }
    
    fn is_umlaut(x: &char) -> bool {
        "äÄüÜöÖ".chars().any(|y| y == *x)
    }
    
    fn valid(line: &str) -> bool {
        line.chars().all(|c| !is_vowel(&c)) && line.chars().filter(is_umlaut).fuse().nth(1).is_some()
    }
    
    fn main() {
        // Create a path to the desired file
        let path = Path::new("c.txt");
        let display = path.display();
        // Open the path in read-only mode, returns `io::Result<File>`
        let file = match File::open(&path) {
            Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
            Ok(file) => file,
        };
        let reader = BufReader::new(file);
        for line in reader.lines() {
            match line {
                Ok(line) => {
                    if valid(&line) {
                        println!("{}", line)
                    }
                }
                Err(e) => println!("ERROR: {}", e),
            }
        }
    }