【问题标题】:How do I convert a single character String to a char?如何将单个字符串转换为字符?
【发布时间】:2022-01-07 05:15:46
【问题描述】:

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

let mut letter = String::new();

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

【问题讨论】:

  • 如果你碰巧已经在使用itertoolsletter.chars().exactly_one().expect("not exactly one")

标签: rust


【解决方案1】:

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

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

但它是important to remember that

char 表示 Unicode 标量值,可能与您的想法不符 什么是“性格”。字素簇的迭代可能是什么 你真的想要。例如,考虑字符串H

let y = "H";

let mut chars = y.chars();

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

现在考虑"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());

另见:

【讨论】:

    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2013-10-21
    • 2011-02-04
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多