字符串替换

来源:互联网 发布:cf手游一键领取软件 编辑:程序博客网 时间:2024/06/17 06:26

牛客在线编程题

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
//这里适当说明,本题要求在原来的内存空间内替换修改字符串,空间总大小为length,已经存储的字符串以str指针指向首地址,这题合适的做法
//是从字符串尾部进行替换,这样不会涉及到覆盖问题。

class Solution {public:void replaceSpace(char *str,int length) {        //length 是空间大小        if(str == NULL || length < 0)            return;        //统计空格数        int i =0, spaces = 0;        while(str[i] != '\0'){            if(str[i] == ' '){                spaces++;            }            i++;        }        //从后往前替换        int newIndex = i + spaces * 2;        while(i >= 0){            if(str[i] != ' '){                str[newIndex--] = str[i--];            }            else{                str[newIndex--] = '0';                str[newIndex--] = '2';                str[newIndex--] = '%';                i--;            }        }}};



原创粉丝点击