cracking the coding interview No1.4

1.4Write a method to replace all spaces in a string with’%20’,You may assume that the string has sufficient space

at the end of the string to hold the additional characters,and that you are given the “true” length of the string

(Note:if implementing in Java,please use a character array so that you can perform this operation in place);

Answer:

void replace(char *str)
{
	if (str == NULL)
		return;
	int length = strlen(str);
	if (!length)
		return;
	int count = 0; //calculate the number of blank space
	for (int i = 0; i<length;i++)
	{
		if (str[i]==' ')
			count++;
	}
	int totallength = length + 2 * count;
	str[totallength--] = '\0';
	for (int i = length - 1; i>=0; i--)
	{
		if (str[i] == ' ')
		{
			str[totallength] = '0';
			str[totallength-1] = '2';
			str[totallength-2] = '%';
			totallength -= 3;
		}
		else
		{
			str[totallength] = str[i];
			totallength--;
		}
	}
}




你可能感兴趣的:(cracking the coding interview No1.4)