Tuesday, 5 April 2011

string::find_next()

I met this new starter who has come from Java background. He was upset because he couldn't find string::find_next() as C++ function. He said Java is much more flexible this way. In reality, its not that bad if you look at the definition of find carefully.

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

The first one works as find_next as I show in the example below:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <string>

using namespace
std;

int
main()
{

string someString("Tom is not in. Infact Tom is not going to be in Tomorrow or day after Tomorrow");
string findTheString("Tom");

unsigned
position = 0;

position = someString.find(findTheString);
cout<<"First position of " << findTheString << " is " << position << endl;

//We want to find all the next positions which is after position + findTheString.length()
while(position != string::npos)
{

position = someString.find(findTheString, (position + findTheString.length()));
cout<<"Next position of " << findTheString << " is " << position << endl;
}


return
0;
}



The output is as follows:

Exercise for new programmers:
  1. The last two Tom's are part of 'Tomorrow', how can you make sure they are not printed
  2. The last Tom which is 4294... is equal to -1 or string::npos. How can you stop that being printed without making another check for string::npos
Please dont post answers as they should be trivial exercise and you should be able to figure out without much problems.

No comments:

Post a Comment