The sword refers to the offer-replacement string

Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==NULL||length==0)
    return;
        int org_length=0;
        int number=0;
        int i=0;
        while(str[i]!='\0')
        {
            ++org_length;
            if(str[i]==' ')
            {
                number++;
            }
            i++;
        }
        
        int new_length=org_length+number*2;
        
        int index_new=new_length;
        int index_old=org_length;
        while(index_old>=0&&index_old<index_new)
        {
            if(str[index_old]==' ')
            {
                str[index_new--]='0';
                str[index_new--]='2';
                str[index_new--]='%';
            }
            else
            {
               str[index_new--]=str[index_old];
            }
            --index_old;
        }
}
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528324&siteId=291194637