开发者

check if a pointer has some string c++

I am not good with c++ and I cannot find this anywhere, please apologize me if it is a bad question. I have a pointer and I want to know if some names store in this pointer begins with some specific string. As in python something like (maybe it is a bad example):

if 'Pre' in pointer_name:

This is what I have:

 double t = 0;
 for (size_t i =0; i < modules_.size(); ++i){
    if(module_[i].name() == "pre"){  // here is what I want to introduce the condition
        if (modules_[i].status() == 2){
            std::cout 开发者_运维问答<< module_[i].name() << "exists" << std::endl;
         }
    }
 } 


The equivalent of Python 'Pre' in string_name is:

string_name.find("Pre") != std::string::npos // if using string

std::strstr(pointer_name, "Pre") // if using char*

The equivalent of Python string_name.startswith('Pre') ("begins with some specific string") is:

string_name.size() >= 3 && std::equal(string_name.begin(), string_name.begin() + 3, "Pre"); // if using string

string_name.find("Pre") == 0 // less efficient when it misses, but shorter

std::strncmp(pointer_name, "Pre", 3) == 0 // if using char*

In two of those cases, in practice, you might want to avoid using a literal 3 by measuring the string you're searching for.


Check std::string::find, there are enough good examples. If you are using c-style string, use strstr.


You can use the algorithm header file to do most of things usually one liners in python.

In this case though it might be just easier to use string find method .


If your name variable is of type std::string then you can use name().compare("Pre") == 0 for string comparison.

EDIT: Seems I misunderstood the question, for contains you can use string find, as other said.

Using C style strings, char * is not recommended in C++. They are error prone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜