Remove extra spaces from a string - GeeksforGeeks

19 Apr, 2022
Given a string containing many consecutive spaces, trim all spaces so that all words should contain only a single space between them. The conversion should be done in-place and solution should handle trailing and leading spaces and also remove preceding spaces before common punctuation like full stop, comma and a question mark.
Examples: 
Input: 
str = "   Hello Geeks . Welcome   to  GeeksforGeeks   .    ";
Output: 
"Hello Geeks. Welcome to GeeksforGeeks."

Input: 
str = "GeeksforGeeks";
Output: 
"GeeksforGeeks"
(No change is needed)
This problem is an extension of Remove spaces from a given string
Method 1:
The idea is to maintain 2 pointers. Initially both point to the beginning of the array.
The first pointer keeps track of next position to be filled in output string.
The second pointer is advanced to read all characters of the string one by one.
On finding any non-space character, the character is copied to the location of the first pointer and then both the first and second pointers are advanced.
If non-space character is a full stop, comma or a question mark, we also remove any preceding space before it.
On finding consecutive space characters, one only space is copied to the location of the first pointer and rest are ignored. The leading and trailing spaces are handled separately in the solution.
Below is C++ implementation of above idea.
C++
// C++ program to implement custom trim() function#include <iostream>using namespace std; // Function to in-place trim all spaces in the// string such that all words should contain only// a single space between them.void removeSpaces(string &str){    // n is length of the original string    int n = str.length();     // i points to next position to be filled in    // output string/ j points to next character    // in the original string    int i = 0, j = -1;     // flag that sets to true is space is found    bool spaceFound = false;     // Handles leading spaces    while (++j < n && str[j] == ' ');     // read all characters of original string    while (j < n)    {        // if current characters is non-space        if (str[j] != ' ')        {            // remove preceding spaces before dot,            // comma & question mark            if ((str[j] == '.' || str[j] == ',' ||                 str[j] == '?') && i - 1 >= 0 &&                 str[i - 1] == ' ')                str[i - 1] = str[j++];             else                // copy current character at index i                // and increment both i and j                str[i++] = str[j++];             // set space flag to false when any            // non-space character is found            spaceFound = false;        }        // if current character is a space        else if (str[j++] == ' ')        {            // If space is encountered for the first            // time after a word, put one space in the            // output and set space flag to true            if (!spaceFound)            {                str[i++] = ' ';                spaceFound = true;            }        }    }     // Remove trailing spaces    if (i <= 1)        str.erase(str.begin() + i, str.end());    else        str.erase(str.begin() + i - 1, str.end());} // Driver Codeint main(){    string str = "   Hello Geeks . Welcome   to"                 "  GeeksforGeeks   .    ";     removeSpaces(str);     cout << str;     return 0;}
Output:  
Hello Geeks. Welcome to GeeksforGeeks.
Time complexity of above solution is O(n).Auxiliary Space is O(1) as the conversion is done in-place.
Method  2:Another solution using predefined functions in Python 3: 
Python3
# Python program to Remove# extra spaces from a stringinput_string = \    '   Hello Geeks  .  Welcome ,    Do you love Geeks , Geeks  ? 'output_string = []space_flag = False # Flag to check if spaces have occurred for index in range(len(input_string)):     if input_string[index] != ' ':        if space_flag == True:            if (input_string[index] == '.'                    or input_string[index] == '?'                    or input_string[index] == ','):                pass            else:                output_string.append(' ')            space_flag = False        output_string.append(input_string[index])    elif input_string[index - 1] != ' ':        space_flag = True print (''.join(output_string))
Output:  
Hello Geeks. Welcome to GeeksforGeeks. Do you love Geeks, Geeks?
Time complexity of above solution is O(n). Auxiliary Space is O(n) as another list had to be created. 
Method 3: (Using built-in function)
Java
Javascript
/**Java Program to remove extra spaces from a string**/ public class GFG {  public static void main(String args[]) {    String str = "   Hello Geeks  .  Welcome ,    Do you love Geeks , Geeks  ? ";    System.out.println(str.replaceAll("\\s+"," ").trim());  }}
<script> // JavaScript Program to remove// extra spaces from a stringvar str = "   Hello Geeks  .  Welcome ,    Do you love Geeks , Geeks  ? ";document.write(str.replace("\\s+", " ").trim()); // This code is contributed by rdtank </script>
Output: 
Hello Geeks . Welcome , Do you love Geeks , Geeks ?
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Sanjoth Shaw
arora_yash
Vijay Sirra
parascoding
rdtank
simmytarika5
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Check whether two strings are anagram of each other
Caesar Cipher in Cryptography
Top 50 String Coding Problems for Interviews
Length of the longest substring without repeating characters
Reverse words in a given string
How to split a string in C/C++, Python and Java?
Remove duplicates from a given string
Print all the duplicates in the input string