创建一个从字符串中获取字符切片的滑动窗口迭代器

编程入门 行业动态 更新时间:2024-10-20 16:33:24
本文介绍了创建一个从字符串中获取字符切片的滑动窗口迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在寻找使用切片.

我了解如何以这种方式使用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.

更多推荐

创建一个从字符串中获取字符切片的滑动窗口迭代器

本文发布于:2023-11-28 21:02:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:切片   字符串   创建一个   字符   窗口

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!