如何检查字符串是否包含char?

Rob*_*wis 17 c++ stdstring

您好我有一个我读过的文本文件,我必须知道其中一个字符串是否包含[所以我使用过:

if(array[i] == "[")
Run Code Online (Sandbox Code Playgroud)

但问题是,它是不是[[,所以这是行不通的.

你有什么想法来解决这个问题吗?

谢谢

Thi*_* B. 36

看一下文档"string find"

std::string s = "hell[o";
if (s.find('[') != std::string::npos)
    ; // found
else
    ; // not found
Run Code Online (Sandbox Code Playgroud)

  • @AdanVivero,如果您阅读文档的 **返回值** 部分,则“npos”是在找不到此类子字符串时返回的值。 (3认同)

Syn*_*nck 8

从 C++23 开始,您可以使用std::string::contains

#include <string>

const auto test = std::string("test");

if (test.contains('s'))
{
    // found!
}
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,“std::string_view”还有一个“contains”成员函数。这可以让您以很少的成本编写像 std::string_view("aeiou").contains(c)` 这样的代码。 (2认同)

Gou*_*rav 5

我是这样做的。

string s = "More+";

if(s.find('+')<s.length()){ //to find +
    //found
} else {
    //not found
}
Run Code Online (Sandbox Code Playgroud)

即使您想找到多个字符,它也可以工作,但它们应该排在一起。请务必替换''""

string s = "More++";

if(s.find("++")<s.length()){ //to find ++
    //found
} else {
    //not found
}
Run Code Online (Sandbox Code Playgroud)