Rust: remove trailing newline after input

None
Language icon Language: this article is available in: de

When reading data from the stdin / Terminal you often have to deal with a trailing newline (\n → line feed) in the resulting string. You can get rid of this using the simple .pop() function which removes the last character from the string:

use std::io::{Write, stdin, stdout};

fn main() {
    // Intro
    println!("-- INPUT Demo --");
    print!("Please enter something: ");
    stdout().flush().unwrap();

    // Input
    let mut inputvar: String = String::new();                                  
    stdin().read_line(&mut inputvar).expect("Error while data input");         
    inputvar.pop(); // remove trailing newline

    // Output
    println!("Eingabe: {}", inputvar);
}

I even found a more convenient cross-platform solution which can deal with \r (old Mac) and \r\n (Windows):

fn trim_newline(s: &mut String) {
    if s.ends_with('\n') || s.ends_with('\r') {
        s.pop();
        if s.ends_with('\r') {
            s.pop();
        }
    }
}

[Update #1:] There is an even shorter and smarter solution (thanks, Stephan!):

fn trim_newline(s: &mut String) {
    while s.ends_with('\n') || s.ends_with('\r') {
        s.pop();
    }
}

[Update #2:] Another good way but without .pop() and using .trim_end_matches() and .truncate() (thanks, thiez!):

let len = input.trim_end_matches(&['\r', '\n'][..]).len();
input.truncate(len);

2 Kommentare

  • Stephan Sokolow

    Depending on what your requirements are, you might just be able to use this: while s.ends_with('\n') || s.ends_with('\r') { s.pop(); }

    Reply
Kommentar verfassen