match matching chars at beginning of STL string

L

Lars Schouw

How do I elegantly match the first chars in an STL string?

this works but is not very elegant.

#include <string>
#include <iostream>

void main()
{
using namespace std;

string str("ABCabc");

if (str.substr(0, 3).find("ABC") != string::npos)
cout << "match" << endl;

if (str.substr(0, 2).find("AB") != string::npos)
cout << "match" << endl;

if (str.substr(0, 2).find("bc") == string::npos)
cout << "no match" << endl;
}
Lars
 
S

Sousuke

How do I elegantly match the first chars in an STL string?

this works but is not very elegant.

#include <string>
#include <iostream>

void main()
{
        using namespace std;

        string str("ABCabc");

        if (str.substr(0, 3).find("ABC") != string::npos)

Just:

if (str.compare(0, 3, "ABC") == 0)
                cout << "match" << endl;

        if (str.substr(0, 2).find("AB") != string::npos)

if (str.compare(0, 2, "AB") == 0)
                cout << "match" << endl;

        if (str.substr(0, 2).find("bc") == string::npos)

if (str.compare(0, 2, "bc") == 0)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top