C语言错题锦集(持续更新)

牛客网[编程题]替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
在这里插入图片描述

题目分析

由于1个空格占1个字符,但是替换为“%20”话是3个字符。所以需要给字符串增加位置。由于“we are happy”中有2个空格,所以理所当然要增加4个位置,即字符串长度增加4.

算法步骤

1.先确定这个字符串有几个空格。然后根据空格确定新字符串的长度。
2.依次将空格后的字符串往后移动。
3.然后依次补上“%20”这三个字符。

代码

class Solution {
    
    
public:
	void replaceSpace(char *str,int length) {
    
    
	int spacecnt = 0;
	char* cur = str;
	while (*cur)
	{
    
    
		if (*cur == ' ')
		{
    
    
			spacecnt++;
		}
		cur++;
	}
	int newlen = length + spacecnt * 2;
	int end1 = length - 1;
	int end2 = newlen - 1;
	while (end1 != end2)
	{
    
    
		if (str[end1] != ' ')
		{
    
    
			str[end2--] = str[end1--];
		}
		else
		{
    
    
			str[end2--] = '0';
			str[end2--] = '2';
			str[end2--] = '%';
			end1--;
		}
	}
	}
};

猜你喜欢

转载自blog.csdn.net/qq2466200050/article/details/123202928
今日推荐