Wednesday, July 11, 2012

Write a program to replace spaces in a string with %20

Approach to replace spaces in a string with %20

Typically in this problem we are expected to use optimal memory. This requires that we extend the memory where we hold the input string. We start by counting the number of spaces in the input string. Then we compute the new size required (2 * spacecount + length) and extend the input string for the extra space required. As the final step scan the input string from the last and if a space is encountered insert %20. That way we use memory optimally and don't overrun the input string.

C++ program to replace space in a string with %20

#include <iostream>
#include <string>
#include <string.h>
using namespace std;

int main() {
 char str[] = "this is a test string";

 int spacecount = 0;
 int length = strlen(str);
 for ( int i = 0; i < length; i++ ) {
  if ( str[i] == ' ' )
   spacecount++;
 }

 int new_size = 2 * spacecount + length;
 str[new_size] = '\0';

 for ( int i = length - 1; i >= 0; i-- ) {
  if ( str[i] == ' ' ) {
   str[new_size-1] = '0';
   str[new_size-2] = '2';
   str[new_size-3] = '%';
   new_size = new_size - 3;
  }
  else {
   str[new_size-1] = str[i];
   new_size = new_size - 1;
  }
 }

 cout << str << endl;
}
Output:-
this%20is%20a%20test%20string

1 comment :

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top