None
Programmierung

Rust: remove trailing newline after input

by Viktor Garske on April 26, 2019, 11 a.m., with 2 comments
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);
Tags:
Author image
Viktor Garske

Viktor Garske ist der Hauptautor des Blogs und schreibt gerne über Technologie, Panorama sowie Tipps & Tricks.

Comments (2)

Comments are not enabled for this entry.

Avatar Stephan Sokolow

April 26, 2019, 2:05 p.m.

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();
}

Avatar Viktor Garske moderator

April 26, 2019, 2:12 p.m.

Great! I added this solution to the article, thank you!