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. Advertisements

  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. Advertisements

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:
    686
    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,838
    Tim Rentsch
    Sep 23, 2005
  3. =?ISO-8859-1?Q?Martin_J=F8rgensen?=
    Replies:
    5
    Views:
    1,577
    =?ISO-8859-1?Q?Martin_J=F8rgensen?=
    May 6, 2006
  4. tech
    Replies:
    12
    Views:
    1,016
    Jerry Coffin
    Jun 24, 2008
  5. Hongyu
    Replies:
    9
    Views:
    1,228
    James Kanze
    Aug 8, 2008
  6. M.Posseth

    receiving ??? chars instead of "special" chars

    M.Posseth, Nov 15, 2004, in forum: ASP .Net Web Services
    Replies:
    3
    Views:
    502
    Dan Rogers
    Nov 16, 2004
  7. Old Echo
    Replies:
    1
    Views:
    298
    Adam Shelly
    Sep 4, 2008
  8. Jesse B.
    Replies:
    9
    Views:
    467
    Jesse B.
    Mar 27, 2010
Loading...