Search code examples
stringsplitrustlinefeed

How do I remove line feeds / line breaks from std::string::String?


I cannot find something that will do this. What I have so far is only for whitespace:

pub fn minify(&self) {
    println!("Minify task started ... ");
    let mut string_iter = self.mystring.split_whitespace();
    for strings in string_iter {
        println!("{}", strings);
    }
}

mystring is something like:

let mystring = "p {
                  text-align: center;
                  color: red;
                } ";

Solution

  • First, you have to define what a "line feed" is. I choose the character \n. In that case, I'd just use replace:

    println!("{}", string.replace('\n', ""))
    

    This works for for &str and String.

    If you didn't need a new string, I'd split on newlines and print them out:

    pub fn minify(string: &str) {
        for line in string.split('\n') {
            print!("{}", line);
        }
    }