Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
                } ";
like image 629
abdoe Avatar asked Apr 17 '26 07:04

abdoe


2 Answers

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);
    }
}
like image 164
Shepmaster Avatar answered Apr 22 '26 02:04

Shepmaster


You can now do this in-place with either of these two options:

string.retain(|c| c != '\n')

or (nightly only)

string.remove_matches('\n');

Check out this playground to see it working

like image 25
Juan Campa Avatar answered Apr 22 '26 02:04

Juan Campa