Brushing notes (2)-replace spaces

Brushing notes (2)-replace spaces

topic

Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy. The string after replacement is We% 20Are% 20Happy.

Ideas

1. Traverse the string from front to back, if a space is encountered, then replace it

When replacing, it should be noted that the following characters need to be moved backwards, because from '' to '% 20', there are two more characters, so starting from the last character, the position of the two characters is moved backwards in sequence.

2. The condition str [i] == '\ 0' to judge the completion of the string traversal

3. After the replacement, i should continue to traverse from the position of i + 3

Code

class Solution {
public:
	void replaceSpace(char *str,int length) {
        int i=0;
        while(str[i]!='\0')
        {
            if(str[i]==' ')
            {
                str[i]='%';
                length+=2;
                int j=0;
                while(j<length-i-2)
                {
                    str[length-1-j]=str[length-2-1-j];
                    j++;
                }
                str[i+1]='2';
                str[i+2]='0';
                i+=3;
            }
            else i++;
        }
	}
};
Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105058402