gpt4 book ai didi

rust - 将字符串剥离成行,并在Rust中的char范围内找到特定的行

转载 作者:行者123 更新时间:2023-12-03 11:41:49 24 4
gpt4 key购买 nike

目标是修剪一行中的字符串并选择特定范围所在的确切行。
如何在rust中使用迭代器完成此操作?

let my_string = "Some small words, they're this.\nTogether";
let stripped_lines = ["Some small words, they\'re this.", "Together"];
// Important word where the char is located with inclusive range

range = Range {start: 33, end:41}
let chosen_line = "Together"
\n被认为是新行的定界符,而 \由于正在格式化,因此不应被视为。
到目前为止我尝试过的是:
let chosen_line = my_string.lines()
.enumerate()
.map(|(lineno, content)| (lineno + 1, content))
.skip_while(|(lineno, _)| range.start < lineno)
.take_while(|(lineno, _)| range.end >= lineno)
.map(|(_, content)| content)
.collect::<Vec<&'_ str>>();
这没有用。我不知道如何结合枚举行和选择char约束的逻辑。
请注意,该范围仅限于特定的行,并且永远不会在行之间(在不同的行中开始和结束)

最佳答案

您可以通过计算前面有多少个换行符来获得某个字符所在的行(按字节索引):

string[..index].chars().filter(|x| x == '\n').count()
如果范围的起点和终点不在一行中,您想发生什么?
您要输入错误,行索引范围还是仅范围索引开始?
您可以只计算两者,并根据需要适当处理不同行的情况。
注意:
如果您需要在同一字符串中进行多次查找,则对于大型字符串,上述操作可能会很慢。您可以预先计算一次换行列表(将其与字符串一起存储),然后使用二进制搜索:
// once:
let newlines = string.char_indices().filter_map(|(ix,c)| if c == '\n' {Some(ix)} else {None}).collect::<Vec<_>>();
// for each lookup:
newlines.binary_search(&index).unwrap_or_else(|x| x)

关于rust - 将字符串剥离成行,并在Rust中的char范围内找到特定的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62878236/

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