剑指offer:面试4——替换空格

剑指offer:面试4——替换空格

题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

class Solution {
public:
	void replaceSpace(char *str,int length) {
        //if(str== NULL || length<=0)return ;
        int space=0;
        int elem=0;
        int i=0;
        int j;
        
        while(str[i]!='\0')
        {
            if(str[i]==' ')
                ++space;
            ++elem;
            ++i;
        }
      j=elem+space*2;
        if(j>length) return;
        int x=i;
        int y=j;
        while(x>=0&&y>x)
        {
            if(str[x]==' ')
            {
                str[y--]='0';
                str[y--]='2';
                str[y--]='%';
                x--;
            }
            else
            {
                str[y--]=str[x];
                x--;
            }
        }
	}
};

猜你喜欢

转载自blog.csdn.net/MereX/article/details/89196390
今日推荐