How can I convert char to string?
Solution 1:
Use char::to_string
, which is from the ToString
trait:
fn main() {
let string = 'c'.to_string();
// or
println!("{}", 'c');
}
Solution 2:
You can now use c.to_string()
, where c
is your variable of type char
.
Solution 3:
Using .to_string()
will allocate String
on heap. Usually it's not any issue, but if you wish to avoid this and want to get &str
slice directly, you may alternatively use
let mut tmp = [0u8; 4];
let your_string = c.encode_utf8(&mut tmp);