Tuesday, 28 January 2014

Replace spaces in a string with %20

Here's the code to replace all the spaces with %20 in a given string.

  1 #include<iostream> 
  2 using namespace std;
  3 int main() 
  4 { 
  5     int i,len,count=0; 
  6     char *str; 
  7     str=new char[100]; 
  8     cout<<"Enter your string: "; 
  9     gets(str); 
 10     len=strlen(str); 
 11     for(i=0;i<len;i++) 
 12     { 
 13         if(str[i]==' ') 
 14             count++; 
 15     } 
 16     int newlength=len+count*2; 
 17     str[newlength]='\0'; 
 18     for(i=len-1;i>=0;i--) 
 19     { 
 20         if(str[i]==' ') 
 21         { 
 22             str[newlength-1]='0'; 
 23             str[newlength-2]='2'; 
 24             str[newlength-3]='%'; 
 25             newlength=newlength-3; 
 26         } 
 27         else 
 28         { 
 29             str[newlength-1]=str[i]; 
 30             newlength=newlength-1; 
 31         } 
 32     } 
 33     cout<<"String after replacing: "; 
 34     puts(str); 
 35     return 0;
 36 } 

No comments:

Post a Comment