本文介绍了创建一个从字符串中获取字符切片的滑动窗口迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找使用切片.
我了解如何以这种方式使用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.
更多推荐
创建一个从字符串中获取字符切片的滑动窗口迭代器
发布评论