rustHow do you create a Rust string from a character array?
Creating a Rust string from a character array can be done using the String::from_utf8
function. This function takes a &[u8]
as an argument and returns a Result<String, FromUtf8Error>
.
Example code
let chars: &[u8] = &[104, 101, 108, 108, 111];
let string = String::from_utf8(chars).unwrap();
Output example
hello
The code above creates a &[u8]
from the character array [104, 101, 108, 108, 111]
and passes it to the String::from_utf8
function. The unwrap
method is used to convert the Result<String, FromUtf8Error>
into a String
.
Code explanation
&[u8]
: A type of array that contains 8-bit unsigned integers.String::from_utf8
: A function that takes a&[u8]
as an argument and returns aResult<String, FromUtf8Error>
.unwrap
: A method that converts aResult<String, FromUtf8Error>
into aString
.
Helpful links
More of Rust
- How to use regex to match a double quote in Rust?
- How to use regex lookahead in Rust?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to use backslash in regex in Rust?
- How to parse JSON string in Rust?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to make regex case insensitive in Rust?
- How to convert a Rust HashMap to a BTreeMap?
See more codes...