Remove spaces from string before period and comma

I could have a string like:

During this time , Bond meets a stunning IRS agent , whom he seduces .

I need to remove the extra spaces before the comma and before the period in my whole string. I tried throwing this into a char vector and only not push_back if the current char was " " and the following char was a "." or "," but it did not work. I know there is a simple way to do it maybe using trim(), find(), or erase() or some kind of regex but I am not the most familiar with regex.

Upvotes: 2

Views: 1940

Answers (4)

BiagioF
BiagioF

Reputation: 9725

A solution could be (using regex library):

std::string fix_string(const std::string& str) {
  static const std::regex rgx_pattern("\\s+(?=[\\.,])");
  std::string rtn;
  rtn.reserve(str.size());
  std::regex_replace(std::back_insert_iterator<std::string>(rtn),
                     str.cbegin(),
                     str.cend(),
                     rgx_pattern,
                     "");
  return rtn;
}

This function takes in input a string and "fixes the spaces problem".

Here a demo

Upvotes: 1

Christophe
Christophe

Reputation: 73456

First, there is no need to use a vector of char: you could very well do the same by using an std::string.

Then, your approach can't work because your copy is independent of the position of the space. Unfortunately you have to remove only spaces around the punctuation, and not those between words.

Modifying your code slightly you could delay copy of spaces waiting to the value of the first non-space: if it's not a punctuation you'd copy a space before the character, otherwise you just copy the non-space char (thus getting rid of spaces.

Similarly, once you've copied a punctuation just loop and ignore the following spaces until the first non-space char.

I could have written code. It would have been shorter. But i prefer letting you finish your homework with full understanding of the approach.

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 31045

I don't know how to use regex for C++, also not sure if C++ supports PCRE regex, anyway I post this answer for the regex (I could delete it if it doesn't work for C++).

You can use this regex:

\s+(?=[,.])

Regex demo

Upvotes: 1

Slava
Slava

Reputation: 44268

On a loop search for string " ," and if you find one replace that to ",":

std::string str = "...";
while( true ) {
    auto pos = str.find( " ," );
    if( pos == std::string::npos )
         break;
    str.replace( pos, 2, "," );
}

Do the same for " .". If you need to process different space symbols like tab use regex and proper group.

Upvotes: 1

Related Questions