C language wrong questions collection (continuously updated)

Niuke.com [programming question] replace spaces

Topic description

Please implement a function that replaces each space in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.
insert image description here

topic analysis

Since 1 space occupies 1 character, but if it is replaced with "%20", it is 3 characters. So you need to add a position to the string. Since there are 2 spaces in "we are happy", it is natural to increase 4 positions, that is, increase the length of the string by 4.

Algorithm step

1. First determine how many spaces this string has. The length of the new string is then determined based on the spaces.
2. Move the string after the space to the back in turn.
3. Then fill in the three characters of "%20" in turn.

code

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--;
		}
	}
	}
};

Guess you like

Origin blog.csdn.net/qq2466200050/article/details/123202928