gpt4 book ai didi

c++ - 使用 string::find 查找单词的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 15:07:47 25 4
gpt4 key购买 nike

我如何通过字符串查找单词而不是该单词中的每个字符。我的代码在这里,它似乎总是能找到所有 .obj 的东西,即使它是 o 或 b 或 j 或“。”我检查了文档 here但无法找到答案。这是我的代码:

 string &str = *it;

if(it->find(".obj"))
{
cout << "Found .Obj" << endl;
}

我也尝试过使用 string::compare 但失败了。

最佳答案

find 会搜索您作为函数参数传递的完整文本字符串。您误解的是返回值; find 不会返回 true 或 false 来判断它是否找到了您请求的字符串;它返回字符串中找到您请求的子字符串的索引,如果未找到匹配项,则返回 std::string::npos

例如:

std::string a = "foobar.obj";
std::string b = "baz.obj";
std::string c = "qux";
std::string d = ".obj";

a.find(".obj") == 6
b.find(".obj") == 3
c.find(".obj") == std::string::npos // not found
d.find(".obj") == 0

当解释为 bool 值时,除 0 以外的任何整数都被视为“真”——即使是“未找到”的 std::string::npos 值。我认为,这就是您感到困惑的地方。

所以在你的“if”语句中,那么,而不是:

if (it->find(".obj"))

您想进行测试:

if (it->find(".obj") != std::string::npos)

关于c++ - 使用 string::find 查找单词的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com