How to remove newline characters from a String?

Viewed 2921

I'm trying to remove newline characters from a String (file content read from a file) and convert it to a Vec<u8>.

Example input string:

let ss = String::from("AAAAAAAA\nBBBBBBBBB\nCCCCCC\nDDDDD\n\n");
fn parse(s: String) -> Vec<u8> {
    let s = s.chars().skip_while(|c| *c == '\n');
    let sett = s.into_iter().map(|c| c as u8).collect();
    sett
}

While I get no error, skip_while doesn't seem to remove the newline characters from the string. What am I doing wrong here?

1 Answers

You can basically replace the \n from the string then convert it to Vec<u8> with into_bytes()

fn parse(s: String) -> Vec<u8> {
    s.replace("\n", "").into_bytes()
}

If you want to do it with iterators you can do it with filter:

fn parse(s: String) -> Vec<u8> {
    s.chars().filter(|c| *c != '\n').map(|c| c as u8).collect()
}

You can call it like following:

use std::str::from_utf8;

fn main() {
    let my_string = String::from("AAAAAAAA\nBBBBBBBBB\nCCCCCC\nDDDDD\n\n");
    let parsed_string = parse(my_string.clone());
    println!("{:?}", from_utf8(&parsed_string));
}

Playground

Related