gpt4 book ai didi

string - 在 char 之后查找字符串中的下一个 char 边界索引

转载 作者:行者123 更新时间:2023-11-29 08:18:56 24 4
gpt4 key购买 nike

给定字符串 s 字符开始处的索引 i:

let s = "abc 好 def";
let i = 4;

获取该字符后的索引的最佳方法是什么,以便我可以对字符串进行切片并获取 abc 好?在代码中:

let end = find_end(s, i);
assert_eq!("abc 好", &s[0..end]);

(注意,+ 1 不起作用,因为它假设字符只有 1 个字节长。)

我目前有以下内容:

fn find_end(s: &str, i: usize) -> usize {
i + s[i..].chars().next().unwrap().len_utf8()
}

但我想知道我是否遗漏了什么并且有更好的方法?

最佳答案

你可以使用 char_indices获取下一个索引而不是使用 len_utf8在角色上,尽管最后一个角色有一个特例。

我会使用方便的 str::is_char_boundary() 方法。这是一个使用它的实现:

fn find_end(s: &str, i: usize) -> usize {
assert!(i < s.len());
let mut end = i+1;
while !s.is_char_boundary(end) {
end += 1;
}
end
}

Playground link

通常我会让这样的函数返回 Option<usize>如果在 s 末尾使用索引调用它,但现在我只是断言。

在许多情况下,而不是显式调用 find_end使用 char_indices 进行迭代可能有意义,它为您提供每个索引以及字符;尽管如果您想知道当前字符的结尾有点烦人。

关于string - 在 char 之后查找字符串中的下一个 char 边界索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com