Remove Spaces from String or Sentence Program in C++

Advertisements

Prev Tutorial Next Tutorial

C++ Program to Remove Spaces from String or Sentence

To wire this code we need to ask user for enter any sentense. Next we start checking space If space will be found, then start placing the next character from the space to the back until the last character and continue to check for next space to remove all the spaces present in the string.
We will not modify original string instead we will create a new string having all characters of input string except spaces.

Examples To Remove Spaces from a String in C++

Example

Input: Hitesh Kumar
Output: HiteshKumar

Program Execution

  • The program takes a sentence and stores in 'str' array.
  • Using a for loop, if a space is encountered it is removed by shifting elements to the left.
  • The resultant string is printed.

To understand below example, you have must knowledge of following C++ programming topics; String in C++, for remove space here we use For Loop in C++ and Array in C++.

Example of Code

Enter Any String: Sitesbay Make Easy Learning
String After Removing Spaces: SitesbayMakeEasyLearning

C++ Program to Swap Two Strings using Third Variable

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>

void main()
{
   
clrscr();
	char str[80];
	int i=0, len, j;
	cout<<"Enter Any String: ";
	gets(str);
	len=strlen(str);
	for(i=0; i<len; i++)
	{
		if(str[i]==' ')
		{
			for(j=i; j<len; j++)
			{
				str[j]=str[j+1];
			}
		len--;
		}
	}
	cout<<"String After Removing Spaces: "<<str;
	getch();
}

Output

Enter Any String: This is my Fist Code
String After Removing Spaces: ThisismyFirstCode
c++ program to remove space from strings

Remove Spaces from a String in C++

Remove Spaces from a String in C++

#include<iostream.h>
#include<conio.h>
#include<string.h>

void main()
{
    char input[100], output[100];
    int i, j;
     
    cout<<"Enter any string \n";
    cin.getline(input, 500);
     
    for(i = 0, j = 0; input[i] != '\0'; i++)
{
        if(input[i] != ' ')
		{
        // If current character is not a space character, 
        // copy it to output String
	    output[j++] = input[i];
	}
    }
    output[j] = '\0';

    cout<<"Input String are: "<<input<<endl;
    cout<<"String without spaces: "<<output;

    getch();
}

Output

Input String are: Hitesh Kumar
String without spaces: HiteshKumar
c++ program to remove space from string
Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements