拆分一个字符串并返回 Vec<String>; [英] Split a string and return Vec&lt;String&gt;

查看:23
本文介绍了拆分一个字符串并返回 Vec<String>;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拆分一个字符串并从我的函数中返回 Vec.它必须是 Vec 而不是 Vec<&str> 因为我不能返回 Vec<&str>,我可以吗?但是,如果可以,我该怎么做?

I want to split a string and return Vec<String> from my function. It has to be Vec<String> and not Vec<&str> because I can't return Vec<&str>, can I? If I can, though, how can I do that?

let var1: Vec<&str> = my_string.split("something").collect();
let res = var1.iter().map(|x| x.to_string());
// I want to return Vec<String>

我尝试了不同的版本,但遇到了error: mismatched types 和其他类型的类似错误.有没有更简单的方法?

I've tried different versions but gotten error: mismatched types and other kinds of similar errors. Is there an easier way?

推荐答案

不需要创建中间Vec<&str>,只需映射to_string()code> 然后使用 collect() :

You don't need to create an intermediate Vec<&str>, just map to_string() and use collect() after that:

let res: Vec<String> = my_string.split("something").map(|s| s.to_string()).collect();

这篇关于拆分一个字符串并返回 Vec<String>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆