Came across Java code and wanted to implement it with C/C++ code:
Given a C string, replace each space of it with "%20" with the following prototype:
void replaceSpace(char s[], int len);
The good things in the original Java code are: in-place transform without any additional data structure. So I am trying to do the same. The following is my version:
void replaceSpace(char s[], int len)
{
int nSpace = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == ' ')
nSpace++;
}
int newLen = len + nSpace * 2;
s[newLen] = '\0';
for (int i = len - 1; i >= 0; i--)
{
if (s[i] == ' ')
{
s[newLen - 1] = '0';
s[newLen - 2] = '2';
s[newLen - 3] = '%';
newLen = newLen - 3;
} else {
s[newLen - 1] = s[i];
newLen = newLen - 1;
}
}
}
Line 11 gave runtime error on VS2008: "stack around varible corrupted", because the C string "str[]" can not be resized/expanded. Can I still achieve what the Java code does without (1) changing the function signature, and (2) without using any additional data structure? I found my hands are tied behind with C/C++.