您的位置:首页 > 其它

cracking the coding interview No1.4

2014-10-19 16:08 393 查看
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--;
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: