获取字符串中任意值范围首次出现的索引



我试图找到字符串中第一个元音的索引(仅限英语/ASCII)。我需要提取这个索引以便稍后使用(在本例中返回)。如此:

let s = String::from("cats");
let vowels = ['a', 'e', 'i', 'o', 'u'];
for v in vowels {
let index = s.to_lowercase().find(v);
if let Some(i) = index {
return i;
}
break;
}

这工作得很好,但我觉得应该有一个更简洁的方法来做到这一点。我尝试的每个在线程序都返回一个bool值,表示在元音中存在匹配或迭代器,而不是字符串中的索引。

.chars()迭代器上使用.position()方法:

let string = "cats".to_owned();
let vowels = ['a', 'e', 'i', 'o', 'u'];
if let Some(index) = string.chars().position(|c| vowels.contains(&c)) {
println!("found first vowel at position: {}", index);
}

请注意,这将反转您的迭代,因为您的原始代码将返回字符串中的第一个"a",即使在它之前有其他元音。


如果我没有指出字符索引与字节索引之间的区别,我也会疏忽。如果您只使用ASCII文本,那么没有区别,但是如果您想要unicode感知并且希望"元音是第n个字符",那么您将需要使用.char_indices().find()来代替:

let string = "ćats".to_owned(); // ć is a multi-byte character
let vowels = ['a', 'e', 'i', 'o', 'u'];
if let Some(index) = string.chars().position(|c| vowels.contains(&c)) {
println!("found first vowel at character: {}", index);
}
if let Some((index, _)) = string.char_indices().find(|(i, c)| vowels.contains(&c)) {
println!("found first vowel at byte offset: {}", index);
}
found first vowel at character: 1
found first vowel at byte offset: 2

你想要什么取决于你如何使用索引。如果稍后要索引字符串,则需要字节偏移量(例如,获取元音:&string[..index]之前的子字符串)。

最新更新