如何在Rust中找到字符串中字符的索引?

MrC*_*der 6 string indexing character rust

我有一个值为"Program"的字符串,我想在该字符串中找到字符'g'的索引.

小智 15

虽然比我想要的更复杂,但另一个解决方案是使用Chars迭代器及其position()功能:

"Program".chars().position(|c| c == 'g').unwrap()
Run Code Online (Sandbox Code Playgroud)

find在接受的解决方案中使用的是返回字节偏移量,而不一定是字符的索引.它适用于基本的ASCII字符串,例如问题中的字符串,并且当与多字节Unicode字符串一起使用时它将返回一个值,将结果值视为字符索引会导致问题.

这有效:

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"
Run Code Online (Sandbox Code Playgroud)

这不起作用:

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 "?"
Run Code Online (Sandbox Code Playgroud)

  • Find 返回起始字节索引,因此不应将其用作字符索引。因此,不应将其与“chars().skip()”一起使用,而应将其用于切片:“let g: String = my_string[g_index..].chars().take(1).collect();”无论您使用哪种字符,都可以正常工作。 (2认同)

met*_*ame 8

您正在寻找findString 的方法。要查找'g'in 的索引,"Program"您可以执行

"Program".find('g')
Run Code Online (Sandbox Code Playgroud)

找到文件