match matching chars at beginning of STL string

Discussion in 'C++' started by Lars Schouw, Mar 25, 2010.

  1. Lars Schouw

    Lars Schouw Guest

    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
     
    Lars Schouw, Mar 25, 2010
    #1
    1. Advertising

  2. Lars Schouw

    Sousuke Guest

    On Mar 25, 6:33 pm, Lars Schouw <> wrote:
    > 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)

    >                 cout << "no match" << endl;}
    >
    > Lars
     
    Sousuke, Mar 26, 2010
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Stormbringer
    Replies:
    11
    Views:
    515
    Bengt Richter
    Dec 23, 2003
  2. Kosio

    Floats to chars and chars to floats

    Kosio, Sep 16, 2005, in forum: C Programming
    Replies:
    44
    Views:
    1,309
    Tim Rentsch
    Sep 23, 2005
  3. tech
    Replies:
    12
    Views:
    742
    Jerry Coffin
    Jun 24, 2008
  4. Hongyu
    Replies:
    9
    Views:
    930
    James Kanze
    Aug 8, 2008
  5. Jesse B.
    Replies:
    9
    Views:
    244
    Jesse B.
    Mar 27, 2010
Loading...

Share This Page