Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the first character of a string in Rust? [duplicate]

Tags:

rust

In JavaScript, I'd write:

s.charAt(0)

What would it be in Rust? How should I handle the s.length == 0 case?

like image 431
Stepan Yakovenko Avatar asked Jun 04 '16 23:06

Stepan Yakovenko


People also ask

Can you index a string in Rust?

Indexing into a string is often a bad idea because it's not clear what the return type of the string-indexing operation should be: a byte value, a character, a grapheme cluster, or a string slice. It's one of the reasons why the Rust compiler does not allows the direct access to characters in strings.

How do you parse a string in Rust?

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().

Are strings mutable in Rust?

Rust owned String type, the string itself lives on the heap and therefore is mutable and can alter its size and contents.

How to remove first and last characters of a string in rust?

This tutorial explains multiple ways to remove the first and last characters of a string in Rust. There are multiple ways we can do it. String slice range This example removes the first and last character and returns the string. using a range of a string length starting from 1..string.length-1

Why can't rust handle Unicode characters?

The main problem here is that Rust's strings are encoded in UTF-8, a variable-length encoding for Unicode characters. Being variable in length, the memory position of the nth character can't determined without looking at the string.

Why can't I Index a string in rust?

The correct approach to doing this sort of thing in Rust is not indexing but iteration. The main problem here is that Rust's strings are encoded in UTF-8, a variable-length encoding for Unicode characters. Being variable in length, the memory position of the nth character can't determined without looking at the string.

What is a string in rust?

API documentation for the Rust `String` struct in crate `std`. ... A UTF-8 encoded, growable string. The String type is the most common string type that has ownership over the contents of the string. It has a close relationship with its borrowed counterpart, the primitive str.


1 Answers

Use s.chars().next(). This will return None if the string is empty or Some(c) otherwise.

like image 167
Francis Gagné Avatar answered Oct 10 '22 04:10

Francis Gagné