我正在 Rust 中对字符串进行一些处理,并且我需要能够从该字符串中提取最后一组字符。换句话说,给定如下所示的字符串:
some|not|necessarily|long|name
Run Code Online (Sandbox Code Playgroud)
我需要能够获取该字符串的最后一部分,即“name”并将其放入另一个字符串或 &str 中,方式如下:
let last = call_some_function("some|not|necessarily|long|name");
Run Code Online (Sandbox Code Playgroud)
这样最后就等于“名称”。
有没有办法做到这一点?是否有一个字符串函数可以轻松完成此操作?如果没有(查看文档后,我怀疑是否有),那么如何在 Rust 中做到这一点?
如何i32从Rust的单行输入中提取两个s?在Python中我可以读两个int像:
a, b = map(int, input().split()) # "2 3" => a=2 and b=3
Run Code Online (Sandbox Code Playgroud)
从Rust 1.3.0开始,我可以运行以下内容来读取一个i32:
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok().expect("read_line panic");
let n: i32 = s.trim().parse().ok().expect("parse panic");
Run Code Online (Sandbox Code Playgroud) 我需要拆分另一个String(不&str)String:
use std::str::Split;
fn main() {
let x = "".to_string().split("".to_string());
}
Run Code Online (Sandbox Code Playgroud)
为什么我会遇到此错误以及如果我必须对字符串进行操作,如何避免它?
error[E0277]: the trait bound `std::string::String: std::ops::FnMut<(char,)>` is not satisfied
--> src/main.rs:4:32
|
4 | let x = "".to_string().split("".to_string());
| ^^^^^ the trait `std::ops::FnMut<(char,)>` is not implemented for `std::string::String`
|
= note: required because of the requirements on the impl of `std::str::pattern::Pattern<'_>` for `std::string::String`
Run Code Online (Sandbox Code Playgroud)
根据# Derefstix- beginners IRC频道,这可能是1.20.0-夜间失败的一个例子.如何在Rust中拆分字符串?不按地址分割的问题String,不是&str.
我想只用分隔符将字符串拆分一次并将其放入元组中.我试过了
fn splitOnce(in_string: &str) -> (&str, &str) {
let mut splitter = in_string.split(':');
let first = splitter.next().unwrap();
let second = splitter.fold("".to_string(), |a, b| a + b);
(first, &second)
}
Run Code Online (Sandbox Code Playgroud)
但我一直被告知,second活得不够久.我想这是因为splitter它只存在于功能块内部,但我不确定如何解决这个问题.如何强制second进入功能块之外的现有?或者是否有更好的方法只分裂一次字符串?
我试图在 Rust 中使用空格和,. 我试着做
let v: Vec<&str> = "Mary had a little lamb".split_whitespace().collect();
let c: Vec<&str> = v.split(',').collect();
Run Code Online (Sandbox Code Playgroud)
结果:
let v: Vec<&str> = "Mary had a little lamb".split_whitespace().collect();
let c: Vec<&str> = v.split(',').collect();
Run Code Online (Sandbox Code Playgroud) 我有一个输入:
let b = String::from("1 2 4 5 6");
Run Code Online (Sandbox Code Playgroud)
我的任务是将每个值的指数函数作为输出返回:
let output = "2.718281828459045 7.38905609893065 54.598150033144236 148.4131591025766 403.4287934927351";
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个任务。如何解析每个值并使用 exp 函数并发送结果字符串?