Removing spaces from a string
RemoveSpaces() takes a character array (string) as an input parameter and returns the string without spaces.
For example
If the input string is “Saad Bin Saulat”, then it will return “SaadBinSaulat”.
Summary of RemoveSpaces()
A for loop starts from the 0th index of the string and iterates till end. The end of the string is indicated by the NULL character ‘\0’ which is present at the end of every string. At each iteration of the for loop, the character is checked – if the character is a space then the whole string is shifted one index back by the second for loop. This is done every time when a space is encountered.
for ( int i = 0; i < strlen(str); i++)
{
if ( str[i] == ' ' )
{
for ( int j = i; j < strlen(str); j++ )
{
str[j] = str[j+1];
}
i = i - 1;
}
}
return str;
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
char * RemoveSpaces( char str[] )
{
for ( int i = 0; i < strlen(str); i++)
{
if ( str[i] == ' ' )
{
for ( int j = i; j < strlen(str); j++ )
{
str[j] = str[j+1];
}
i = i - 1;
}
}
return str;
}
int main()
{
char str[] = " Saad Bin Saulat ";
cout << "String after the removal of spaces : " << RemoveSpaces( str ) << endl;
_getche();
return 0;
}
Output
String after the removal of spaces : SaadBinSaulat
0 comments:
Post a Comment