gpt4 book ai didi

rust - 如何将单个字符 String 转换为 char?

转载 作者:行者123 更新时间:2023-12-05 02:35:11 25 4
gpt4 key购买 nike

这个问题看似微不足道,但我找不到答案。假设 letter 是单个字符串,我如何将 letter 转换为 char?

let mut letter = String::new();

io::stdin()
.read_line(&mut letter)
.expect("Failed to read line");

最佳答案

一种解决方案是使用 chars method .这将返回字符串切片的 char 上的迭代器。

let letter_as_char: char = letter.chars().next().unwrap();
println!("{:?}", letter_as_char);

但它是important to remember that

char represents a Unicode Scalar Value, and might not match your ideaof what a ‘character’ is. Iteration over grapheme clusters may be whatyou actually want. For example, Consider the String H

let y = "H";

let mut chars = y.chars();

assert_eq!(Some('H'), chars.next());
assert_eq!(None, chars.next());

Now consider "y̆"

let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());

另见:

关于rust - 如何将单个字符 String 转换为 char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70616894/

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