Avatar of ambuli
ambuliFlag for United States of America

asked on 

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.
C++C

Avatar of undefined
Last Comment
ambuli
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of ambuli
ambuli
Flag of United States of America image

ASKER

Thanks JKR.  Didn't know about the rfind.
Avatar of ambuli
ambuli
Flag of United States of America image

ASKER

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.
Avatar of jkr
jkr
Flag of Germany image

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

Avatar of ambuli
ambuli
Flag of United States of America image

ASKER

Thank you!
C++
C++

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.

58K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo