如何将一个元素字符串转换为char? [英] How can I convert a one element string into a char?

查看:61
本文介绍了如何将一个元素字符串转换为char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个元素& str 转换为 char 。我能够提出这个解决方案,该解决方案也适用于 String

I need to convert a one element &str into char. I was able to come up with this solution that also works for String:

fn main() {
    let comma: &str = ",";
    let my_char = comma.chars().nth(0).unwrap();
   
    assert_eq!(my_char, ',');
}

有更好或更短的方法吗?

Is there a better or shorter way to do it?

推荐答案

我想不出什么大的改进,但有几点注意事项:

No huge improvements I can think of, but a few notes:


  • 您可以将 .nth(0)替换为 .next(),这基本上是相同的。

  • 理想情况下,您不应使用 .unwrap(),因为如果字符串为空,则程序将出现恐慌。

  • 如果您真的必须惊慌,最好使用 .expect( msg),这样可以用户对为什么感到惊慌的更好想法。

  • You could replace .nth(0) with .next(), which does basically the same thing.
  • You should ideally not use .unwrap(), since if the string is empty, your program will panic.
  • If you really must panic, ideally use .expect("msg"), which will give users a better idea of why you panicked.

将这些因素结合在一起:

Taking those together:

fn main() {
    let comma: &str = ",";
    let my_char = comma.chars().next().expect("string is empty");

    assert_eq!(my_char, ',');
}

唯一要注意的是一个元素在某种程度上是危险的有话要说。例如,é 有一个 char ,但是é有两个(第一个是预先编写的U + 00E9,第二个是常规的 e ,然后是U + 0301结合◌́)。

The only other thing to note is that "one element" is a somewhat dangerous thing to talk about. For example, "é" has one char, but "é" has two (the first is a pre-composed U+00E9, whilst the second is a regular e followed by a U+0301 combining ◌́).

这篇关于如何将一个元素字符串转换为char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆