简体   繁体   中英

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.

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

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 .

If your word has several g 's you could use enumerate to find all indices:

"ඞggregate"
    .chars()
    .enumerate()
    .filter(|(_, c)| *c == 'g')
    .map(|(i, _)| i)
    .collect::<Vec<_>>();  // [1, 2, 5]

If the string contains ASCII characters only:

"aggregate"
    .bytes()
    .enumerate()
    .filter(|(_, b)| *b == b'g')
    .map(|(i, _)| i)
    .collect::<Vec<_>>();  // [1, 2, 5]

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM