rust 字符串检索下标
时间: 2023-05-08 16:58:01 浏览: 91
在 Rust 中,字符串是一个 UTF-8 编码的 Unicode 字符序列,与其他大部分语言不同,Rust 中的字符串不是原生类型,而是通过标准库的 String 类型来表示的。
Rust 中可以通过下标来访问字符串中的某个字符,但需要注意的是,Rust 中的字符串是不可变类型,因此我们不能直接通过下标来修改其中的字符。
示例代码如下:
```rust
let s = String::from("hello");
let c = s.chars().nth(0); // 获取第一个字符
if let Some(ch) = c {
println!("{}", ch);
}
```
此外,我们还可以通过使用字符串的迭代器进行遍历,如:
```rust
for ch in s.chars() {
println!("{}", ch);
}
```
如果需要查找某个字符串在目标字符串中的位置,可以使用字符串的 find 方法,返回值为该字符在字符串中的下标,如果找不到则返回 None。例如:
```rust
let s = String::from("hello world");
if let Some(pos) = s.find("world") {
println!("'world' found at position {}", pos);
} else {
println!("'world' not found");
}
```
注意,如果需要在字符串中查找单个字符,则可以使用 chars() 方法将字符串转成字符迭代器,依次遍历,查找目标字符。如果要查找子串,则使用 find 方法会更加方便。