创建一个从字符串中获取字符切片的滑动窗口迭代器 [英] Creating a sliding window iterator of slices of chars from a String
本文介绍了创建一个从字符串中获取字符切片的滑动窗口迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找使用我了解如何以这种方式使用Windows:
I understand how to use windows this way:
fn main() {
let tst = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
let mut windows = tst.windows(3);
// prints ['a', 'b', 'c']
println!("{:?}", windows.next().unwrap());
// prints ['b', 'c', 'd']
println!("{:?}", windows.next().unwrap());
// etc...
}
但是解决这个问题时我有点迷路:
But I am a bit lost when working this problem:
fn main() {
let tst = String::from("abcdefg");
let inter = ? //somehow create slice of character from tst
let mut windows = inter.windows(3);
// prints ['a', 'b', 'c']
println!("{:?}", windows.next().unwrap());
// prints ['b', 'c', 'd']
println!("{:?}", windows.next().unwrap());
// etc...
}
本质上,我正在寻找如何将字符串转换为可以与window方法一起使用的char切片.
Essentially, I am looking for how to convert a string into a char slice that I can use the window method with.
推荐答案
此解决方案将为您效用. (游乐场)
This solution will work for your purpose. (playground)
fn main() {
let tst = String::from("abcdefg");
let inter = tst.chars().collect::<Vec<char>>();
let mut windows = inter.windows(3);
// prints ['a', 'b', 'c']
println!("{:?}", windows.next().unwrap());
// prints ['b', 'c', 'd']
println!("{:?}", windows.next().unwrap());
// etc...
println!("{:?}", windows.next().unwrap());
}
字符串可以遍历其字符,但这不是一个切片,因此您必须将其收集到一个vec中,然后将其强制转换为一个切片.
String can iterate over its chars, but it's not a slice, so you have to collect it into a vec, which then coerces into a slice.
这篇关于创建一个从字符串中获取字符切片的滑动窗口迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文