Make the frequent cases fast and the rare case correct

Program to remove space within strings

The approach is to use a pointer to the string and traverse this string using a for loop. Every time the pointer encounters a string its assigned to the string.

#include <iostream>
#include <cstring>
using namespace std;

void SpaceRemover(char str[], int len)
 int i,j;
 char *out;
 //pointer to string

 //traverse the string using a for loop
 //if no space is found assign pointer to string
 if(*out!=' ')
 //end of string is made NULL
 cout<<"\nAfter space is removed="<<str<<"\n";

int main()
 char str[100];
 cout<<"\nEnter the string = ";
 cin.getline(str, 100);

 SpaceRemover(str, strlen(str));

 return 0;

We can also use isspace() function to check for a space.


laptop:~/code$ ./a.out

Enter the string = algorithms is f u n

After space is removed=algorithmsisfun

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: