Monday, July 27, 2009

C++ simple string question?

Here's my problem:


call the function findand() to find the substring "and" in str and (if it is found), copy it to mid. If "and" was found, the findand() function will print mid and return the position of "and" process(); otherwise, it will print "no 'and' found" and return -1 to process(). (The return value of findand() determines whether you call the next two functions.)





My real question is, how can you copy the "and" to mid? What would be the boundaries for the substring function?


For example I have:





int findand (string str)


{


string mid;





string::size_type pos;





pos = str.find ("bean", 0);


if (pos == str.npos) {


file_out %26lt;%26lt; "No 'and' found" %26lt;%26lt; endl;


return -1;


}


else {


mid = str.substr (pos, pos - 1);


file_out %26lt;%26lt; mid %26lt;%26lt; endl;


return pos;


}


}





The problem lies with mid = str.substr (pos, pos - 1);


So if you can correct it I would be quite grateful.

C++ simple string question?
Well the parameters of the substr function are (position, length). So you pass in the position, and then the number of characters to copy. So pos-1 isn't what you want to use for the second parameter. If you want to copy the substring "and", you should probably use 3:





mid = str.substr(pos, 3);





Which will copy three characters starting at pos.





Incidentally, this code always copies the string "and" into mid. So a simplification would be:





mid = "and";
Reply:Why are you using pos - 1 as the number of characters to pull out of str into mid? Shouldn't you be using the size of the string you looked for?





Also, why are you looking for "bean" but saying "No 'and' found"?


No comments:

Post a Comment