0

I want to remove the extra space after a string in c++ without removing the spaces between. EG. "The Purple Dog " How do I remove the space to make it "The Purple Dog"

Ive tried to iterate through and find the space just at the end, but I have had no success.

Ken White
  • 123,280
  • 14
  • 225
  • 444

1 Answers1

0

Assuming you're using std::string, you could use find_last_not_of:

#include <string>
#include <iostream>

int main()
{
    std::string str = "The Purple Dog      ";
    
    // "g" in "Dog"
    size_t lastNonSpace = str.find_last_not_of(" "); 
    
    // Remove all the spaces
    str.resize(lastNonSpace + 1); 
    
    // Print ";" at the end so we can see the spaces are gone 
    std::cout << str << ";" << std::endl; 

    return 0;
}

edit: More efficient approach