Coders Packet

Remove all spaces from string in C++

By Sneha Gupta

Program to remove all the spaces from the string entered by the user and return it to the user

For example:

If user entered the string "How are you" then 

output - "howareyou"

In the above example, all the whitespaces are removed from the string.

C++ Code:

#include 
#include
using namespace std;
 
// Function to remove all spaces from a given string
void rem(char *str)
{
    // To keep track of non-space character count
    int c = 0;
 
    /* Traverse the given string. If current character
     is not space, then place it at index 'c++'*/
    for (int i = 0; str[i]; i++)
        if (str[i] != ' ')
            str[c++] = str[i]; // here c is incremented
    str[c] = '\0';
}
int main()
{
    char str[100];
    cout<<"Enter string"<<endl;
    cin.get(str, 100);
    rem(str);
    cout << str;
    return 0;
}

Output:

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Sneha Gupta (Snehagpta015)

Download packets of source code on Coders Packet