HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How do I get the first character out of a string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howthecharacteroutstringgetfirst

Problem

I want to get the first character of a std::str. The method char_at() is currently unstable, as is String::slice_chars.

I have come up with the following, but it seems excessive to get a single character and not use the rest of the vector:

let text = "hello world!";
let char_vec: Vec = text.chars().collect();
let ch = char_vec[0];

Solution

UTF-8 does not define what "character" is so it depends on what you want. In this case, chars are Unicode scalar values, and so the first char of a &str is going to be between one and four bytes.

If you want just the first char, then don't collect into a Vec, just use the iterator:
let text = "hello world!";
let ch = text.chars().next().unwrap();


Alternatively, you can use the iterator's nth method:
let ch = text.chars().nth(0).unwrap();


Bear in mind that elements preceding the index passed to nth will be consumed from the iterator.

Context

Stack Overflow Q#30811107, score: 228

Revisions (0)

No revisions yet.