Removing spaces from a string
Remove() takes 2 parameters as its input
parameter: first is the character array (string) and the second
is the character to remove.It returns the string without the specificed
character.
For example
If
the input string is “Saad Bin Saulat”, and the characetr to remove is ‘a’,then
it will return “SdBinSult”.
char * Remove( char * str , char ch )
{
for ( int i = 0; i < strlen(
str ); i++ )
{
if ( str[i] == ch )
{
for ( int j = i; j < strlen(
str ); j++ )
{
str[j]
= str[j+1];
}
i = i
- 1;
}
}
return str;
}
Summary of Remove()
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 equal to the character to
remove, then the whole string is shifted one index back by the second for loop.
After the end of for loop
the string in str is returned from
the function.
Example (C++)
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
char * Remove( char * str , char ch )
{
for ( int i = 0; i < strlen(
str ); i++ )
{
if ( str[i] == ch )
{
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 at start : " << str <<
endl;
cout << "String after removal of character ' ' :
" << Remove( str , ' ') << endl;
cout << "String after removal of character 'a' :
" <<Remove( str , 'a') << endl;
_getche();
return 0;
}
Output
String
at start :
Saad Bin Saulat
String
after removal of character ' ' :
SaadBinSaulat
String
after removal of character 'a' :
SdBinSult
0 comments:
Post a Comment