std-method

Validate C-string encoding

A valid C string may contain bytes that are not valid UTF-8. to_str checks UTF-8; to_string_lossy replaces invalid sequences for display. Lossy conversion is not appropriate for round-tripping arbitrary bytes. Expected stdout (not executed): true � Common mistake: Assuming NUL termination implies valid Unicode.

Formal Syntax & Structure

rust syntaxrust
c_string.to_str()

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::ffi::CStr;    let raw = CStr::from_bytes_with_nul(b"\xff\0").unwrap();    println!("{} {}", raw.to_str().is_err(), raw.to_string_lossy());}
Rust Reference