Tied my hands behind: replace C string spaces with "%20"

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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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++.
Last edited on
You're assuming that the buffer passed in is large enough to be expanded that way. It almost certainly won't be.

That aside, the algorithm looks ok.


EDIT: Your crash is for exactly the reason I predicted, it's not because of that signature.
Last edited on
Topic archived. No new replies allowed.