Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the index of a character in a string in Rust?

I have a string with the value "Program", and I want to find the index of character 'g' in that string.

like image 416
MrCoder Avatar asked May 06 '17 12:05

MrCoder


People also ask

How do you find the index of a certain character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

Can I access a string using index?

Strings are ordered sequences of character data, 00:15 and the individual characters of a string can be accessed directly using that numerical index. String indexing in Python is zero-based, so the very first character in the string would have an index of 0 , 00:30 and the next would be 1 , and so on.

How do you find the length of a string in Rust?

Overview. The length of a string is the number of characters that make up that string. We can get the length of a string in Rust using the len() method.


2 Answers

Although a little more convoluted than I would like, another solution is to use the Chars iterator and its position() function:

"Program".chars().position(|c| c == 'g').unwrap()

find used in the accepted solution returns the byte offset and not necessarily the index of the character. It works fine with basic ASCII strings, such as the one in the question, and while it will return a value when used with multi-byte Unicode strings, treating the resulting value as a character index will cause problems.

This works:

let my_string = "Program";
let g_index = my_string.find("g");   // 3
let g: String = my_string.chars().skip(g_index).take(1).collect();
assert_eq!("g", g);   // g is "g"

This does not work:

let my_string = "プログラマーズ";
let g_index = my_string.find("グ");    // 6
let g: String = my_string.chars().skip(g_index).take(1).collect();
assert_eq!("グ", g);    // g is "ズ"
like image 74
Enigma Avatar answered Oct 08 '22 18:10

Enigma


You are looking for the find method for String. To find the index of 'g' in "Program" you can do

"Program".find('g')

Docs on find.

like image 33
metame Avatar answered Oct 08 '22 19:10

metame