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 get a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to replace strings using Rust regex?
- How to use regex with bytes in Rust?
- How to calculate the inverse of a matrix in Rust?
See more codes...