C++ check and remove last word from a string

Hi there,

How can I remove a particular word in a string only if it is the last one.  If the last word is not the one we need then we do nothing.

For example,

"This is a string AND we would remove the last word from it AND"

Here, how can I remove the last AND.
ambuliAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jkrCommented:
E.g. like

#include <string>
#include <iostream>
using namespace std;

string remove_last_word_if(string& sentence, const string& word) {

  string::size_type pos;

  pos = sentence.rfind(word); // 'rfind()' begins at the end, makes things easier

  if (string::npos != pos) sentence.erase(pos, word.length());

  return sentence;
}

int main() {

  string sentence = "This is a string AND we would remove the last word from it AND";

  cout << sentence << endl;
  cout << remove_last_word_if(sentence,"AND") << endl;

  return 0;
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ambuliAuthor Commented:
Thanks JKR.  Didn't know about the rfind.
0
ambuliAuthor Commented:
But, what can we do to prevent if the last word is not the word to be removed.
for example, if the string is
string sentence = "This is a string AND we would remove the last word from it"
Then I do not want to remove the AND.
0
jkrCommented:
Ah, OK so you want to ensure it is the *very* last word? You can do that by checking that 'pos + word.length()' equal the size of the sentence, i.e.

  if (string::npos != pos && sentence.length() == pos + word.length()) sentence.erase(pos, word.length());

Open in new window

0
ambuliAuthor Commented:
Thank you!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.