Remove extra spaces from the String in C++

C++ Programs

Problem: Write a C++ program to remove extra spaces from the given string.

Example:

Input:  This   is a   ball.
Output: This is a ball.

To remove redundant white spaces from a given string, we form a new string by concatenating only the relevant characters.

We skip the multiple white spaces using the while loop and add only the single last occurrence of the multiple white spaces.

#include <iostream>
using namespace std;

int main() {
    //input a string
    string str;
    cout << "Enter a string: ";
    getline(cin, str);
        
    //declare an empty string
    string nstr;
    
    //loop through the characters of the input string
    for(int i=0; i<str.length();  ){
        //check if character is white space
        if(str[i] == ' '){
            /* 
              *do not include the white space, if-
              *it is at the trailing or leading position
            */
            if(i==0 || i==str.length()-1){
                i++;
                continue;
            }
            
            /*
              *if space is inbetween then skip it-
              *except the last occurrence
            */
            while(str[i+1] == ' ')
                i++;
        }
        
        //concatenate the character to the new string
        nstr += str[i++];
    }
    
    //output the new string
    cout << "New String: " << nstr;
    return 0;
}

Output:

Enter a string: This     is    a  website.
New String: This is a website.

This program also removes the trailing and leading white spaces if there is any in the input string.

Leave a Reply

Your email address will not be published. Required fields are marked *