/*******************************************************
Write a method to replace all spaces in a string with ‘%20’
Note: every space is replaced with 3 characters, causing the extension of the string by 2 * SpCnt.
Complexity: O(2n)
Mod Time: 4.20, 2012
Copyright: Ben
*******************************************************/
#include<stdio.h>
#include<stdlib.h>
#define STRING_MAX_LEN 10000
int main(void)
{
int i, j, Offset;
char s[STRING_MAX_LEN];
char ch;
//this marks the indices of <sp>
int sp[STRING_MAX_LEN / 2]; //in case all char are spaces.
//number of <sp>
int SpCnt = 0;
int StLen = 0;
freopen("String.txt", "r", stdin);
//keep reading until the end of file.
while((ch = fgetc(stdin)) != EOF)
{
if(ch == ' ')
{
sp[SpCnt++] = StLen;
}
s[StLen++] = ch;
}
s[StLen] = '\0';
sp[SpCnt] = StLen; //the pseudo count.
printf("Original:%s\n", s);
//the final char is separately handled.
s[sp[SpCnt] + SpCnt * 2] = '\0';
//replacement
for(i = SpCnt; i > 0; i--)
{
Offset = i * 2;
for(j = sp[i] - 1; j > sp[i - 1] ; j--)
{
s[j + Offset] = s[j];
}
//replace <sp> with "%20"
s[sp[i - 1] + Offset] = '0';
s[sp[i - 1] + Offset - 1] = '2';
s[sp[i - 1] + Offset - 2] = '%';
}
printf("Modified:%s\n", s);
fclose(stdin);
return 0;
}
Write a method to replace all spaces in a string with ‘%20’
Note: every space is replaced with 3 characters, causing the extension of the string by 2 * SpCnt.
Complexity: O(2n)
Mod Time: 4.20, 2012
Copyright: Ben
*******************************************************/
#include<stdio.h>
#include<stdlib.h>
#define STRING_MAX_LEN 10000
int main(void)
{
int i, j, Offset;
char s[STRING_MAX_LEN];
char ch;
//this marks the indices of <sp>
int sp[STRING_MAX_LEN / 2]; //in case all char are spaces.
//number of <sp>
int SpCnt = 0;
int StLen = 0;
freopen("String.txt", "r", stdin);
//keep reading until the end of file.
while((ch = fgetc(stdin)) != EOF)
{
if(ch == ' ')
{
sp[SpCnt++] = StLen;
}
s[StLen++] = ch;
}
s[StLen] = '\0';
sp[SpCnt] = StLen; //the pseudo count.
printf("Original:%s\n", s);
//the final char is separately handled.
s[sp[SpCnt] + SpCnt * 2] = '\0';
//replacement
for(i = SpCnt; i > 0; i--)
{
Offset = i * 2;
for(j = sp[i] - 1; j > sp[i - 1] ; j--)
{
s[j + Offset] = s[j];
}
//replace <sp> with "%20"
s[sp[i - 1] + Offset] = '0';
s[sp[i - 1] + Offset - 1] = '2';
s[sp[i - 1] + Offset - 2] = '%';
}
printf("Modified:%s\n", s);
fclose(stdin);
return 0;
}