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.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of