簡體   English   中英

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

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

我有一個值為“Program”的字符串,我想在該字符串中找到字符“g”的索引。

雖然比我想要的更復雜,但另一個解決方案是使用Chars迭代器及其position()函數:

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

在接受的解決方案中使用的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"

這不起作用:

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

您正在尋找String的find方法。 要在"Program"找到'g'的索引,你可以這樣做

"Program".find('g')

發現的文件

如果您的單詞有幾個g ,您可以使用enumerate來查找所有索引:

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

如果字符串僅包含 ASCII 字符:

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

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM