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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top