To convert from char to str

Asked 2 years ago, Updated 2 years ago, 54 views

There is a method to convert from char to string in trust, but is there a method to convert from char to str?

rust

2022-09-30 14:50

2 Answers

An array b for storing encoded characters a and using the array b as an argument for the encode_utf8 method of the character a can be converted to a variable of b.

fnmain(){
    letc = 'a'; // character 'a'

    let mut b = [0;4]; // Array b for storing characters

    Letts = c.encode_utf8(&mutb); // Array b contains the character c encoded in UTF8 and returns s of &mutstr pointing to b

    println!("{},s);// character 'a' is displayed
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=648crest=648671c6&faf6

encode_utf8About the method
https://doc.rust-lang.org/std/primitive.char.html#method.encode_utf8


2022-09-30 14:50

I looked into it, but it seems impossible.

According to the reference, String is UTF-8 while char is encoded with UTF-32.

UTF-32, UTF-16, and UTF-8 interconversion may be easy to understand, but without endian differences, UTF-32 does not simply have a 4-byte UTF-8 code point, so there is no string in memory.This means that str cannot be created.
In fact, no such API is found in the standard library.

If you don't want to save memory, pressing ArrayString may suit your purpose.


2022-09-30 14:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.