简体   繁体   English

为什么std :: string.find()不能用于“<”?

[英]Why won't std::string.find() work for “<”?

I have : 我有 :

#include <iostream>
#include <string>

int main(int argc, const char * argv[])
{

    std::string foo = "<!";

    if (foo.find("<")) {
        std::cout<<"Found";
    }

    return 0;
}

Why won't this code find the "<" ? 为什么这段代码不能找到"<" If I change the line to foo.find("!") , then it is found. 如果我将行更改为foo.find("!") ,则会找到它。 So what is the problem with "<" ? 那么"<"什么问题?

If successful std::string::find() returns the index where its argument is found, not a boolean. 如果成功, std::string::find()将返回std::string::find()其参数的索引,而不是布尔值。

Because "<" is found at index 0 it returns 0, and in a boolean context 0 is false, so the condition fails. 因为在索引0处找到"<" ,它返回0,并且在布尔上下文中,0为false,因此条件失败。 Because "!" 因为"!" is at index 1 it returns 1, and in a boolean context that is true. 在索引1处返回1,并在布尔上下文中为true。

Instead of testing whether find returns true you need to use: 而不是测试find是否返回true,您需要使用:

if (foo.find("<") != std::string::npos) {

npos is the special value reserved to mean "not a position" and find returns it to say the value was not found. npos是保留为表示“非位置”的特殊值, find返回它表示未找到该值。

NB when you want to search for a single character it is better to do exactly that, not search for a string of length one, ie use foo.find('<') instead of foo.find("<") 注意当你想要搜索单个字符时,最好这样做,而不是搜索长度为1的字符串,即使用foo.find('<')而不是foo.find("<")

You could have debugged this for yourself by trying to search for '<' in the string "!<" and you would have found that the result is nothing to do with the specific character you search for, but only where in the string it gets found. 您可以通过尝试在字符串"!<"搜索'<'来调试自己,并且您会发现结果与您搜索的特定字符无关,而只是在字符串中的位置找到。

Your if statement is not checking if you found your substring correctly, try this: 你的if语句没有检查你是否正确找到了你的子串,试试这个:

if (foo.find("<") != std::string::npos)

working example 工作实例

It does find the "<", at position 0, which becomes false in this context. 它确实在位置0处找到“<”,在此上下文中变为false

find returns the index at which it found the argument, or std::string::npos if it can't find the argument. find返回它找到参数的索引,如果找不到参数,则返回std::string::npos You do not check for that in your if statement. 您不在if语句中检查它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM