Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

rust

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<char> = text.chars().collect(); let ch = char_vec[0]; 
like image 222
XAMPPRocky Avatar asked Jun 12 '15 19:06

XAMPPRocky


People also ask

How do I get the first character of a string in Java?

To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.

How do you get rid of the first character in a string in C?

To remove the first character of a string, we can use the char *str = str + 1 in C. it means the string starts from the index position 1. Similarly, we can also use the memmove() function in C like this.

How do you get the first character in a string?

Get the First Character Using the charAt () Method in Java The charAt () method takes an integer index value as a parameter and returns the character present at that index. The String class method and its return type are a char value. The program below shows how to use this method to fetch the first character of a string.

How to extract first n characters from string in Excel?

Extract first n characters from string. Select a blank cell, here I select the Cell G1, and type this formula =LEFT(E1,3) (E1 is the cell you want to extract the first 3 characters from), press Enter button, and drag fill handle to the range you want.

What is the first character index of a string in C++?

Here is an example, that gets the first character a: Note: In C++ Strings are a sequence of characters, so the first character index is 0 and the second character index is 1, etc.

How to extract the last 3 characters from a string?

Tip: If you want to extract the last 3 characters, check From left and specify the number of the characters you want to remove from the strings. 1. Applying this feature will change your original data, you’d better copy them firstly.


1 Answers

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<char>, 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.

like image 61
Steve Klabnik Avatar answered Sep 18 '22 17:09

Steve Klabnik