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 remove them and also handle punctuation marks.

The idea is to iterate through the string’s characters and check if the 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, remove it unless it just after a word or a punctuation mark.

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

C


Download  Run Code

Output:

Hello. This is a C program!!

C++


Download  Run Code

Output:

Hello. This is a C++ program!!

The time complexity of the above solution is O(n), where n is the length of the input string and doesn’t require any extra space for the conversion.