在 Rust 中有没有像 JavaScript 的 substr 这样的方法? [英] Is there a method like JavaScript's substr in Rust?
本文介绍了在 Rust 中有没有像 JavaScript 的 substr 这样的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我查看了 Rust 文档String
但我找不到提取子字符串的方法.
I looked at the Rust docs for String
but I can't find a way to extract a substring.
有没有像 JavaScript 的 substr
在 Rust 中?如果没有,您将如何实施?
Is there a method like JavaScript's substr
in Rust? If not, how would you implement it?
str.substr(start[, length])
最接近的可能是 slice_unchecked
但它使用字节偏移量而不是字符索引并标记为 unsafe
.
The closest is probably slice_unchecked
but it uses byte offsets instead of character indexes and is marked unsafe
.
推荐答案
对于字符,可以使用 s.chars().skip(pos).take(len)
:
For characters, you can use s.chars().skip(pos).take(len)
:
fn main() {
let s = "Hello, world!";
let ss: String = s.chars().skip(7).take(5).collect();
println!("{}", ss);
}
不过要注意 Unicode 字符的定义.
Beware of the definition of Unicode characters though.
对于字节,您可以使用切片语法:
For bytes, you can use the slice syntax:
fn main() {
let s = b"Hello, world!";
let ss = &s[7..12];
println!("{:?}", ss);
}
这篇关于在 Rust 中有没有像 JavaScript 的 substr 这样的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文