Tuesday, March 17, 2009

Working with std::string::substring() method

Though it is a very simple function, but sometimes people(me too) make a mistake when coding thing up. For example we have a std::string strHello

int nPositoinOfSemiColon = strHello.find(";", 0);

find method will find the fist parameter ";" in strHello, starting from second parameter i.e. 0.
Now the nPositoinOfSemiColon will contain either string::npos which means the string provided to find method was not found in strHello. Or in our case, 5 which is the location of ";".

strHello.substr(0, nPositoinOfSemiColon );

will return "Hello", i.e. 5 characters starting from location 0 in strHello.
Now consider

int nPositionOfSecondSemiColon = strHello.find(";", nPositionOfSemiColon);

Well... writing following line of code will... wonder what...

strHello.substr(nPositionOfSemiColon, nPositionOfSecondSemiColon);

CAUSE AN ERROR!!! FOLKS!!! ERR GRR ERROOORRR... a vicious cruel ugly error... heh heh heh...
Poor baby programmers will asK "But why Uncle why???"
Because, of the values in variables at this time are...

nPositionOfSemiColon = 5
AND
nPositionOfSecondSemiColon = 11
That means
strHello.substr(5, 11);

i.e. extract 11 characters starting from location 5 in strHello.
Whereas, 11 is total length of strHello...

The right way to go is

strHello.substr(nPositionOfSemiColon,
nPositionOfSecondSemiColon - nPositionOfSemiColon);

That means
strHello.substr(5, 6); // That means ";WORLD"

Cheers folks... have fun... remember... coding is a noble pursuit... so just keep hitting it hard... savor the wonders and joys of turning real world into programming language codes, and bear the tensions with enough tolerance...

1 comment:

Feel free to talk back...