How to remove newlines from a string Rust

2 Answers

0 votes
fn remove_newlines(s: &str) -> String {
    s.chars()
        .filter(|&c| c != '\n' && c != '\r')
        .collect()
}

fn main() {
    let s = "c# \n  c c++  \n java python\ngo\n";
    let result = remove_newlines(s);

    println!("{}", result);
}

 
  
   
/*
run:
   
c#   c c++   java pythongo
  
*/

 



answered Feb 22 by avibootz
0 votes
fn remove_newlines(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut last_was_space = false;

    for c in s.chars() {
        if c.is_whitespace() {
            if !last_was_space {
                out.push(' ');
                last_was_space = true;
            }
        } else {
            out.push(c);
            last_was_space = false;
        }
    }

    out.trim().to_string()
}

fn main() {
    let s = "c# \n  c c++  \n java python\ngo\n";
    let result = remove_newlines(s);

    println!("{}", result); // result without extra spaces
}

  
   
/*
run:
   
c# c c++ java python go
  
*/

 



answered Feb 22 by avibootz
...