1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Programming Tutorial - C++ Strings

By David Bolton, About.com

6 of 10

More Find Functions and Comparing Strings

These are other variations of the find function.
  • find_first_of() - Find first char in string (public member function)
  • finc_first_not_of() - Find first char not in the string
  • find_last_of() - Find first char in string from the end
  • find_last_not_of() - Find first character not in string from the end
Each of these has overloaded versions for searching for string, char and char *. I've never had to use any of these though if you do a lot of text processing, you may find them useful.

Comparing Strings

Just use == with strings, as if you were comparing two ints. Behind the scenes, the main comparison operator == is defined as
bool operator == (const string& left, const string right) ;
but a comparison like
if (str =="Hello")
could be quite inefficient with this definition because it would have to first convert the char * parameter right to a temporary string object and then copy the value into it. Thankfully there are two overloads which implement a comparison of a string and char * or a char * and string, just to avoid this inefficiency.

The compare function provides more flexibility
This is another overloaded function that allows comparison between parts of strings and char * or other strings. This snippet is from example 4.

Download Example 4

const string s("Humpty Dumpty sat on a wall") ;
if ( s.compare(14,3,"sat",0,3) ==0 )
     cout << "Strings Match" << endl;
   else
      cout << "Strings Don't Match" << endl;
This compares the part of s that starts at position 14 and is 3 chars long with the part of "sat" that starts at position 0 and is also 3 chars long (i.e. "sat") and returns 0 if they match. Don't forget the ==0 or your logic will be inverted and wrong!

On the next page - Template String Functions

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. More Find Functions and Comparing Strings

©2009 About.com, a part of The New York Times Company.

All rights reserved.