Advertisement
Shalfey

Replace spaces with "%20" in C

Apr 19th, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. // Implement the method of replacing all the spaces in the string with substring "%20"
  2. char* replace_spaces(const char *s)
  3. {
  4.     const char SPACE = ' ';
  5.     const char REPLACEMENT[] = "%20";
  6.     unsigned int numOfSpaces = 0;
  7.     for(int i = 0; i < strlen(s); i++)
  8.     {
  9.         if(s[i] == SPACE)
  10.         {
  11.             numOfSpaces++;
  12.         }
  13.     }
  14.     // we have found number of spaces in the string
  15.     // it helps us to define the exact size of modified string
  16.     char* modifiedString = new char[strlen(s) - numOfSpaces + numOfSpaces*strlen(REPLACEMENT) + 1];
  17.     modifiedString[strlen(s) - numOfSpaces + numOfSpaces*strlen(REPLACEMENT)] = '\0';
  18.     for(int sourceStrIdx = 0, modifiedStrIdx = 0; sourceStrIdx < strlen(s); sourceStrIdx++)
  19.     {
  20.         if(s[sourceStrIdx] != SPACE)
  21.         {
  22.             modifiedString[modifiedStrIdx] = s[sourceStrIdx];
  23.             modifiedStrIdx++;
  24.         }
  25.         else
  26.         {
  27.             for(int k = 0; k < strlen(REPLACEMENT); k++)
  28.             {
  29.                 modifiedString[modifiedStrIdx] = REPLACEMENT[k];
  30.                 modifiedStrIdx++;
  31.             }
  32.         }
  33.     }
  34.     return modifiedString;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement