Thứ Ba, 26 tháng 8, 2014

A "C++"program to replaces emptyspaces with some character.

Hi Guys,Welcome

 Aim of this program is to replace an empty space by using a character.for example a string is given like

"shashi kumar",you have space between i and k ,now you need to fill this space with "%20".


Wrong Program:

Here am giving a code that actually doesn't work .But you can observe why that doesn't work in later Program.

#include<iostream.h>
#include<conio.h>
int main()
{
char array[]="shashi kumar";
clrscr();
int i;
for(i=0;array[i]!='\0';i++)
{
    if(array[i]==' ')
    {
    array[i]='%20';                          //line XX

    }
}
cout<<"printing data";
for(i=0;array[i]!='\0';i++)
{
cout<<array[i];
}

return 0;

}

output:
-------------------------


The reason for this is see code at line no xx.

Right Program;


void replace(char [],int);
#include<iostream.h>
#include<conio.h>
int main()
{
clrscr();
char data[]="shashi kumar follow my totorials";
int length=0,i;
for(i=0;data[i]!='\0';i++)
{
length=length+1;
}
replace(data,length);
return 0;
}
void replace(char a[],int l)
{
    int i,j;
    char rep[100];
    for(i=0,j=0;i<l;i++)
    {
        if(a[i]==' ')
        {
         rep[j++]='%';
         rep[j++ ]='2';
         rep[j++]='0';
        }
        else
        {
        rep[j++]=a[i];
        }


    }
    rep[j]='\0';
    //printing string now
    for(i=0;rep[i]!='\0';i++)
    cout<<rep[i];

}


output:

--------------------------------




Không có nhận xét nào:

Đăng nhận xét