user1094865
user1094865

Reputation:

How to remove trailing null characters from String?

I am having issues with removing trailing null characters from UTF-8 encoded strings:

enter image description here

How would one go about removing these characters from a String?

Here is the code I use to create the String from a Vec:

let mut data: Vec<u8> = vec![0; 512];
// populate data
let res = String::from_utf8(data).expect("Found invalid UTF-8");

Upvotes: 20

Views: 15705

Answers (1)

MB-F
MB-F

Reputation: 23637

You can trim custom patterns from a string using trim_matches. The pattern can be a null character:

fn main() {
    let mut data: Vec<u8>  = vec![0; 8];
    
    data[0] = 104;
    data[1] = 105;
    
    let res = String::from_utf8(data).expect("Found invalid UTF-8");
    println!("{}: {:?}", res.len(), res);
    // 8: "hi\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}"
    
    let res = res.trim_matches(char::from(0));
    println!("{}: {:?}", res.len(), res);
    // 2: "hi"
}

This removes 0 from both sides. If you only want to remove trailing 0s use trim_end_matches instead.

Upvotes: 46

Related Questions