gpt4 book ai didi

string - 当将char存储在字符串切片中时,char占用多少字节?

转载 作者:行者123 更新时间:2023-12-03 11:41:24 25 4
gpt4 key购买 nike

我对Rust中的字符串/字符/切片感到困惑。根据文档,一个字符是4个字节,但是下面的程序显示了一个三个字符的字符串,在片中使用了7个字节。似乎在切片中字符的存储效率最高,因此常规的“A”存储为1个字节,而两个汉字字符则分别存储为3个字节。

fn main() {
let s = String::from("A漢字");
let ss = &s[..];
let sbytes = ss.len();
let schars = s.chars().count();
println!("{} is {} characters and {} bytes",ss,schars,sbytes);
}

$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Running `target/debug/test_string`
A漢字 is 3 characters and 7 bytes

最佳答案

我发现对于字符c,您可以知道他们字节将像这样在切片中占用:

let b = c.len_utf8();

关于string - 当将char存储在字符串切片中时,char占用多少字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61909723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com