Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a single character String to a char?

Tags:

rust

This issue seems trivial but I can't find an answer. Assuming that letter is a single character string, how could I convert letter to a char?

let mut letter = String::new();

io::stdin()
    .read_line(&mut letter)
    .expect("Failed to read line");
like image 851
ntedvs Avatar asked Oct 23 '25 19:10

ntedvs


1 Answers

One solution is to use chars method. This return an iterator over the chars of a string slice.

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

But it is important to remember that

char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you 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());

See also:

  • How to iterate over Unicode grapheme clusters in Rust?
like image 161
Abdul Niyas P M Avatar answered Oct 26 '25 09:10

Abdul Niyas P M