[Question] P51 sword refers to offer: replace spaces-please implement a function to replace each space in the string with "%20". For example, if you enter "We are happy.", then enter "We%20are%20happy.".

P51 sword refers to offer: replace spaces

Please implement a function to replace each space in the string with "%20". For example, if you enter "We are happy.", then enter "We%20are%20happy.".

code show as below:

Idea: Replace the spaces in the string with "%20" from back to front.
Time complexity: O(n)

/*  替换空格  */
/*  length为字符数组string的总容量  */
void ReplaceBlank(char* string, int length)
{
    
    
	/*  判断非法测试  */
	if (string == nullptr || length <= 0)
		return;
	/*  OriginalLength为字符串string的实际长度  */
	int OriginalLength = 0;
	int NumberOfBlank = 0;
	int i = 0;
	while (string[i] != '\0')
	{
    
    
		OriginalLength++;
		if (string[i] == ' ')
			NumberOfBlank++;
		i++;
	}
	/*  NewLength为字符串string中的空格替换成'%20'之后的长度  */
	int NewLength = OriginalLength + NumberOfBlank * 2;
	/*  数组string放不下替换之后的字符串,则不进行替换  */
	if (NewLength > length)
		return;
	int IndexOfOiginal = OriginalLength;
	int IndexOfNew = NewLength;
	while (IndexOfOiginal >= 0 && IndexOfNew > IndexOfOiginal)
	{
    
    
		if (string[IndexOfOiginal] == ' ')
		{
    
    
			string[IndexOfNew--] = '0';
			string[IndexOfNew--] = '2';
			string[IndexOfNew--] = '%';
		}
		else
			string[IndexOfNew--] = string[IndexOfOiginal];
		IndexOfOiginal--;
	}
}

int main()
{
    
    
	/*
	char a[] = "We are happy.";
	导致栈溢出,因为这样定义会默认数组大小
	利用下标访问数组会非法访问
	*/

	char a[18] = "We are happy.";
	cout << "替换前:" << a << endl;
	ReplaceBlank(a, 18);
	cout << "替换后:" << a << endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/114293729