Replace spaces with %20

Replace spaces (click the link to enter the title)

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.

Problem analysis: The original string contains spaces, and the length of the changed string increases, and spaces are replaced with %20.

Method 1: We directly use the C++ string to create a string class object, and then traverse the original string. When a non-space is encountered, that is, insert a character at the end of the string class object. If a space is encountered, the string class object will be inserted. Insert the "%20" string at the end of the .

class Solution {
    
    
public:
	void replaceSpace(char *str,int length) {
    
    
		//创建一个string类的val对象
        string val;
        //遍历原字符串
        for(size_t i = 0; i < length; i++)
        {
    
    
        	//当遇到非空格时,将原字符串对应位置的字符尾插到val对象上
            if(str[i] != ' ')
                val.push_back(str[i]);
            //当遇到空格时,将“%20”字符串尾插到val对象上
            else
                val.append("%20");
        }
        //最后检验的时str,所以我们将val进行拷贝,拷贝给str。
        strcpy(str, val.c_str());
	}
};

Method 2: By moving the string, we can calculate the size of the replaced string by counting the number of spaces, and then move the data of the original string backwards in turn. When spaces are encountered, insert them in turn. '0', '2', '%' can be used.

class Solution {
    
    
public:
	//此函数用于获取字符串中空格的个数
    int spaceNum(char* arr,int sz)
    {
    
    
        int count = 0;
        for(size_t i = 0; i < sz; i++)
        {
    
    
            if(arr[i] == ' ')
                count++;
        }
        return count;
    }
	void replaceSpace(char *str,int length) {
    
    
        //获取空格的个数
        int space_count = spaceNum(str,length);
        
        //新字符串的长度
        //原始字符串长度 + 空格个数 * 2 = 替换后的字符串长度
        int new_size = length + (space_count * 2);
        
        //定义两个char类型的指针,old_ptr指针指向原字符串长度的末尾
        //new_ptr指针指向替换字符串后新长度的末尾
        char* old_ptr = str + length;
        char* new_ptr = str + new_size;
        
        //进入循环,依次往后挪动数据
        while(old_ptr >= str && new_ptr >= str)
        {
    
    
            if(*old_ptr == ' ')
            {
    
    
                *new_ptr-- = '0';
                *new_ptr-- = '2';
                *new_ptr-- = '%';
                old_ptr--;
            }
            else
                *new_ptr-- = *old_ptr--;
        }
    }
};

In fact, there are other methods for this question, which are not recommended here, because it is more cumbersome, such as: using some built-in functions of c, and then splitting and splicing the strings.

Guess you like

Origin blog.csdn.net/weixin_43202123/article/details/120183876