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

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 "ズ"

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)