如何检查字符串是否包含 Rust 中的子字符串? [英] How to check if a string contains a substring in Rust?
本文介绍了如何检查字符串是否包含 Rust 中的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试查找子字符串是否在字符串中.在 Python 中,这涉及到 in
操作符,所以我写了这段代码:
I'm trying to find whether a substring is in a string. In Python, this involves the in
operator, so I wrote this code:
let a = "abcd";
if "bc" in a {
do_something();
}
我收到一条奇怪的错误消息:
I get a strange error message:
error: expected `{`, found `in`
--> src/main.rs:3:13
|
3 | if "bc" in a {
| _____________-^
4 | | do_something();
5 | | }
| |_____- help: try placing this code inside a block: `{ a <- { do_something(); }; }`
该消息表明我将其放入一个块中,但我不知道该怎么做.
The message suggests that I put it in a block, but I have no idea how to do that.
推荐答案
Rust 没有这样的操作符.您可以使用 String::contains代码>方法
代替:
Rust has no such operator. You can use the String::contains
method instead:
if a.contains("bc") {
do_something();
}
这篇关于如何检查字符串是否包含 Rust 中的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文