Remove all extra spaces from a string

Write a program to in-place remove all extra spaces from a string. There maybe leading spaces, trailing spaces, or consecutive spaces between words of the string. The solution should be able to remove them and also handle punctuation marks.


The idea is to iterate through the characters of the string and check if current character is a space, non-space character, or a punctuation mark. If it is a punctuation mark, any preceding space if present, is removed. If it is a space, we remove it if it’s not just after a word or a punctuation mark.

Below is C/C++ implementation of it. The solution keeps track of next empty position in output string to facilitate the algorithm and handles the leading and trailing spaces separately.


Download   Run Code


Download   Run Code


Hello. This is C++ program!!

The time complexity of above solution is O(n) and no extra space is used for the conversion.

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon

Leave a Reply

Notify of