【字符串】替换空格【剑指offer】

替换空格

http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423

#include <stdio.h>
#include <iostream>

using namespace std;


class Solution{
public:
    void replaceSpace(char str[],int length) {
        //合法性检验
        if(str == NULL || length <= 0)
            return;
        //计算实际长度和替换后的长度
        int i=0, count=0;
        while(str[i] != '\0')
        {
            if(str[i] == ' ')
                count++;
            ++i;
        }
        int oriIndex = i, newIndex = oriIndex + count * 2; 

        if(newIndex < oriIndex)
            return;

        //逆序移动  循环结束条件两个指针指到相同位置
        while(newIndex != oriIndex)
        {
            //旧索引处发现空格,新索引处替换并添加
            if(str[oriIndex] == ' ')
            {
                str[newIndex--] = '0';
                str[newIndex--] = '2';
                str[newIndex--] = '%';
            } 
            else//未发现 复制原先位置字符
            {
                str[newIndex] = str[oriIndex];
                newIndex--;
            }  
            //无论是否发现,旧索引都需要向前移动一个索引
            --oriIndex;        
        }
    }   
};

int main()
{
    char str[100] = " We are happy.";
    int len = sizeof(str) / sizeof(char);
    Solution sol;
    sol.replaceSpace(str,100);
    cout<<str<<endl;
}
全部评论

相关推荐

Southyeung:我说一下我的看法(有冒犯实属抱歉):(1)简历不太美观,给我一种看都不想看的感觉,感觉字体还是排版问题;(2)numpy就一个基础包,机器学习算法是什么鬼?我感觉你把svm那些写上去都要好一点。(2)课程不要写,没人看,换成获奖经历;(3)项目太少了,至少2-3个,是在不行把网上学习的也写上去。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务