[Data Structure and Algorithm] Replace spaces in strings

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

ubuntu linux, vscode debugging passed

#include <iostream>
#include <string.h>
using namespace std;


class solution{

public :
    void blankreplace(char * str,int length)
    {
        //字符串为空 
        if(str==nullptr)
        {
            cout<<"  空指针"<<endl;
            return;
        }
        cout<<"1111111111111"<<endl;
        //边界检查
        int originallen =0;
        int count_blank=0;
        int last_length=0;
        char *p=str;
      while(*p!='\0')
        {
            cout<<"while "<<endl;
            if(*p++==' '){
                count_blank++;
            }
            
            originallen++;
            cout<<"originallen"<<originallen<<endl;
        }
        last_length=originallen+2*count_blank;

        if(last_length<length)
        {
            return;
        }

cout<<"last_length:"<<last_length<<endl;
        char * plast =str+last_length;
        while(*p!=*plast)
        {
            cout<<*p<<endl;
            if(*p==' ')
            {
                *plast--='0';
                *plast--='2';
                *plast--='%';
            }
            else{
                *plast--=*p;
            }
            p--;
        }



    }
};

int main()
{
    char test[50];
    test[0]='\0';
   char *p=NULL;
   cout<<"null p "<<endl;
    strcpy(test,"we are happy");
    p=test;
   solution so;

   so.blankreplace(p,strlen(test));
cout<<"--->"<<test<<endl;

}
Published 19 original articles · Likes0 · Visits 383

Guess you like

Origin blog.csdn.net/qinchun/article/details/105335578